class GamepadManagerClass
{

    constructor()
    {
        this.haveEvents = 'ongamepadconnected' in window;
        this.controllers = {};

        if (!this.haveEvents)
        {
            setInterval(() => { this.scangamepads(); } , 500);
        }

        window.addEventListener("gamepadconnected", (e) => { this.connecthandler(e); });
        window.addEventListener("gamepaddisconnected", (e) => { this.disconnecthandler(e); });

        this.XBOXController = {
            A: 0,
            B: 1,
            X: 2,
            Y: 3, 
            LB: 4,
            RB: 5,
            LT: 6,
            RT: 7,
            BACK: 8,
            START: 9,
            LS: 10,
            RS: 11,
            DPAD_UP: 12,
            DPAD_DOWN: 13,
            DPAD_LEFT: 14,
            DPAD_RIGHT: 15,
            LS_X: 0,
            LS_Y: 1,
            RS_X: 2,
            RS_Y: 3
        };

        
    }

    connecthandler(e)
    {
        this.addgamepad(e.gamepad);
    }

    addgamepad(gamepad)
    {
        this.controllers[gamepad.index] = gamepad;
    }

    disconnecthandler(e)
    {
        this.removegamepad(e.gamepad);
    }

    removegamepad(gamepad)
    {
        delete this.controllers[gamepad.index];
    }

    updateStatus()
    {
        if (!this.haveEvents)
        {
            this.scangamepads();
        }

        for (var j in this.controllers)
        {
            var controller = this.controllers[j];
            for (var i = 0; i < controller.buttons.length; i++)
            {
                var val = controller.buttons[i];
                var pressed = val == 1.0;
                if (typeof(val) == "object")
                {
                    pressed = val.pressed;
                    val = val.value;
                }
                //var pct = Math.round(val * 100) + "%";
            }

            for (i = 0; i < controller.axes.length; i++)
            {
                //a.innerHTML = i + ": " + controller.axes[i].toFixed(4);
                //a.setAttribute("value", controller.axes[i] + 1);
            }
        }
    }

    scangamepads()
    {
        var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
        for (var i = 0; i < gamepads.length; i++)
        {
            if (gamepads[i])
            {
                if (gamepads[i].index in this.controllers)
                {
                    this.controllers[gamepads[i].index] = gamepads[i];
                } else {
                    this.addgamepad(gamepads[i]);
                }
            }
        }
    }
}

var GamepadManager = new GamepadManagerClass();