using UnityEngine;
using UnityEngine.UI;
using XInputDotNetPure;

namespace Assets.Scripts.GamepadInterface
{
    public class TwoPlayerController : MonoBehaviour
    {
        public Text Player1;
        public Text Player2;

        private PlayerIndex[] _players;
        private bool _foundGamepads;

        void Start ()
        {
		    FindPlayers();
        }

        void FindPlayers()
        {
            var test = Controller.FindControllers();
            if (test == null) return;
            _players = test;
            _foundGamepads = true;
        }

        void Update ()
        {

            for (var i = 0; i < 2; ++i)
            {
                if (i == 0) CheckState(_players[i], Player1);
                if (i == 1) CheckState(_players[i], Player2);
            }
        }

        void CheckState(PlayerIndex index, Text display)
        {
            var state = Controller.GetState(index);
            display.text = state.IsConnected.ToString();

            var output = "";
            output += string.Format("({0:n2},{1:n2}), ({2:n2},{3:n2}), A: {4}, B: {5}, X: {6}, Y: {7}", state.Left.X, state.Left.Y, state.Right.X, state.Right.Y, state.A.Hold, state.B.Hold, state.X.Hold, state.Y.Hold);
            output += string.Format("\nBack: {0}, Start: {1}", state.Back.Hold, state.Start.Hold);
            output += string.Format("\nLB: {0}, RB: {1}, LeftClick: {2}, RightClick: {3}", state.LeftBumper.Hold, state.RightBumper.Hold, state.Left.Click.Hold, state.Right.Click.Hold);
            output += string.Format("\nLT: {0}, RT: {1}", state.LeftTrigger.Value, state.RightTrigger.Value);
            output += string.Format("\nUp: {0}, Down: {1}, Left: {2}, Right: {3}", state.Dpad.Up.Hold, state.Dpad.Down.Hold, state.Dpad.Left.Hold, state.Dpad.Right.Hold);
            display.text = output;

            state.SetRumble(index, state.LeftTrigger.Value, state.RightTrigger.Value);

        }
    }
}
