using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using XboxCtrlrInput;

namespace PlayerInput
{
    public class XboxControllerInputSource<TTarget> : InputSource<TTarget> where TTarget : MonoBehaviour
    {
        private static List<XboxController> allControllers;
        public static IEnumerable<XboxController> AllControllers { get { return allControllers; } }
        static XboxControllerInputSource()
        {
            allControllers = new List<XboxController>()
            {
                XboxController.First,
                XboxController.Second,
                XboxController.Third,
                XboxController.Fourth,
            };
        }

        private Dictionary<InputButton, XboxButton> buttonMapping;
        private Dictionary<InputAxis, XboxAxis> axisMapping;

        private XboxController controller;
        public XboxController Controller { get { return controller; } }

        public XboxControllerInputSource(XboxController controller)
        {
            this.controller = controller;

            buttonMapping = new Dictionary<InputButton, XboxButton>()
            {
                { InputButton.MenuSelect, XboxButton.A },
                { InputButton.MenuCancel, XboxButton.B },

                //{ InputButton.UseItem, XboxButton.A },
                //{ InputButton.PickA, XboxButton.LeftBumper },
                //{ InputButton.PickB, XboxButton.RightBumper },

                //{ InputButton.AnimalSelector, XboxButton.LeftBumper },
            };

            axisMapping = new Dictionary<InputAxis, XboxAxis>()
            {
                { InputAxis.MenuX, XboxAxis.LeftStickX },
                { InputAxis.MenuY, XboxAxis.LeftStickY },

                { InputAxis.RakeX, XboxAxis.RightStickX },
                { InputAxis.RakeY, XboxAxis.RightStickY },

                { InputAxis.MoveX, XboxAxis.LeftStickX },
                { InputAxis.MoveY, XboxAxis.LeftStickY },

                //{ InputAxis.Throttle, XboxAxis.RightTrigger },
                //{ InputAxis.RevThrottle, XboxAxis.LeftTrigger },
            };
        }

        protected override void VibrateInternal(float left, float right)
        {
            XCI.SetVibration(controller, left, right);
        }

        public override bool ButtonPressedThisFrame(InputButton button)
        {
            return XCI.GetButtonDown(buttonMapping[button], controller);
        }

        public override bool ButtonReleasedThisFrame(InputButton button)
        {
            return XCI.GetButtonUp(buttonMapping[button], controller);
        }

        public override bool ButtonDown(InputButton button)
        {
            return XCI.GetButton(buttonMapping[button], controller);
        }

        public override float Axis(InputAxis axis)
        {
            return XCI.GetAxis(axisMapping[axis], controller);
        }
    }
}
