using InControl;
using UnityEngine;

public class PlayerActions : PlayerActionSet
{
	public PlayerAction Left { get; private set; }
	public PlayerAction Right { get; private set; }
	public PlayerOneAxisAction Rotate { get; private set; }

	public PlayerAction Move { get; private set; }
	public PlayerAction Attack { get; private set; }

	public PlayerActions(int playerNumber)
	{
		Left = CreatePlayerAction("Move Left");
		Right = CreatePlayerAction("Move Right");
		Rotate = CreateOneAxisPlayerAction(Left, Right);

        Rotate.StateThreshold = 0.2f;

		Move = CreatePlayerAction("Jump");
		Attack = CreatePlayerAction("Interact");

        SetGamepad(playerNumber);
		SetDefaultValues(playerNumber);
	}

    private void SetGamepad(int playerNumber)
    {
        bool foundDevice = false;

        foreach (InputDevice d in InputManager.Devices)
        {
            if (d.IsAttached)
            {
                if (Device == null && playerNumber == 1)
                {
                    Device = d;
                    break;
                }
                else if (!foundDevice)
                    foundDevice = true;
                else if (Device == null)
                {
                    Device = d;
                    break;
                }
            }
        }
    }

    public void VibrateDevice(float intensity)
    {
        if (Device != null)
            Device.Vibrate(intensity);
    }

    public void StopDeviceVibration()
    {
        if (Device != null)
            Device.StopVibration();
    }

	public void SetDefaultValues(int playerNumber)
	{
		Left.ClearBindings();
		Left.AddDefaultBinding(InputControlType.LeftStickLeft);
		Left.AddDefaultBinding(InputControlType.DPadLeft);
		Left.AddDefaultBinding(playerNumber == 1 ? Key.A : Key.LeftArrow);

		Right.ClearBindings();
		Right.AddDefaultBinding(InputControlType.LeftStickRight);
		Right.AddDefaultBinding(InputControlType.DPadRight);
		Right.AddDefaultBinding(playerNumber == 1 ? Key.D : Key.RightArrow);

		Move.ClearBindings();
		Move.AddDefaultBinding(InputControlType.Action1);
		Move.AddDefaultBinding(playerNumber == 1 ? Key.F: Key.P);

		Attack.ClearBindings();
		Attack.AddDefaultBinding(InputControlType.Action3);
		Attack.AddDefaultBinding(playerNumber == 1 ? Key.G : Key.O);
	}
}