using System.Collections.Generic;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.UI;
using UnityEngine.InputSystem.Utilities;
using InputDevice = UnityEngine.InputSystem.InputDevice;

namespace Conjure.Input
{
    public class MenuInputManager : SerializedMonoBehaviour
    {
        [SerializeField, Required] private InputSystemUIInputModule inputSystemUIInputModule;
        [SerializeField, Required] private InputServerReference inputServerReference;

        // Start is called before the first frame update
        void Start()
        {
            inputSystemUIInputModule.actionsAsset.devices = new ReadOnlyArray<InputDevice>();
        }

        public void OnJoin(int playerSeat)

        {
            if (inputSystemUIInputModule.actionsAsset.devices == null)
            {
                return;
            }

            InputManagerServer inputManagerServer = inputServerReference.Value.GetComponent<InputManagerServer>();
        
            List<InputDevice> devices =
                new List<InputDevice>(inputSystemUIInputModule.actionsAsset.devices.Value.ToArray());

            PlayerEnum player = inputManagerServer.GetPlayerFromInt(playerSeat);

            // shouldn't be reachable
            if (player == PlayerEnum.None)
            {
                return;
            }

            InputDevice currentDevice = FindDeviceById(inputManagerServer.GetDeviceIdFromPlayerEnum(player));
        
            // shouldn't be reachable
            if (currentDevice is not null)
            {
                devices.Add(currentDevice);
            }

            inputSystemUIInputModule.actionsAsset.devices = new ReadOnlyArray<InputDevice>(devices.ToArray());
        }

        public void OnLeave(int playerSeat)
        {
            if (inputSystemUIInputModule.actionsAsset.devices == null)
            {
                return;
            }
        
            InputManagerServer inputManagerServer = inputServerReference.Value.GetComponent<InputManagerServer>();

            if (playerSeat == 0 && inputManagerServer.GetNumberPlayers() == 0)
            {
                inputSystemUIInputModule.actionsAsset.devices = new ReadOnlyArray<InputDevice>();
                return;
            }
        
            InputDevice currentDevice = FindDeviceById(inputManagerServer.GetDeviceIdFromPlayerEnum(PlayerEnum.Player1));
            inputSystemUIInputModule.actionsAsset.devices = new ReadOnlyArray<InputDevice>(new []{currentDevice});
        }

        private InputDevice FindDeviceById(int deviceId)
        {
            foreach (InputDevice currentDevice in InputSystem.devices)
            {
                if (currentDevice.deviceId == deviceId)
                {
                    return currentDevice;
                }
            }

            return null;
        }
    }
}