/**
 * Created by bmonkey on 8/18/15.
 */
import _ from 'lodash';

var last_pressed = {};
var interval_ids = {};
var timeout_ids = {};

const repeat_interval = 80; //ms
const repeat_timeout = 300; //ms

function gamepadHandler(event, connecting) {
    var pad = event.gamepad;
    if (connecting) {
        if (pad.index == 0)
            console.log("Gamepad", pad.index, "connected:", pad);
    } else {
        console.log("Gamepad", pad.index, "disconnected:");
    }
}

function delayedPressed(idx, callback) {
    callback();
    timeout_ids[idx] = setTimeout(function () {
        callback();
        interval_ids[idx] = setInterval(function () {
            callback();
        }, repeat_interval);
    }, repeat_timeout);
}

function clearDelayed(idx) {
    clearInterval(interval_ids[idx]);
    clearInterval(timeout_ids[idx]);
}

function queryGamePads(gamePadCallback) {
    let gamepads = navigator.getGamepads();
    _.each(gamepads, function (pad) {
        if (pad) {
            let pressed = {};
            _.each(pad.buttons, function (button, idx) {
                if (button.pressed) {
                    pressed[idx] = true;
                    if (Object.keys(last_pressed[pad.index]).indexOf(idx.toString()) < 0)
                        gamePadCallback(pad, idx, "pressed");
                }
            });
            _.each(last_pressed[pad.index], function (isPressed, idx) {
                if (Object.keys(pressed).indexOf(idx) < 0)
                    gamePadCallback(pad, idx, "released");
            });
            last_pressed[pad.index] = Object.assign({}, pressed);
        }
    });
}

export {gamepadHandler, queryGamePads, clearDelayed, delayedPressed};
@@ -1167,77 +1167,472 @@
     
-if (Object.keys(last_pressed%5Bpad.index%5D).indexOf(idx.toString()) %3C 0)
+let thisPadsLastPressed = last_pressed%5Bpad.index%5D;%0A                    if (thisPadsLastPressed != null) %7B%0A                        let lastPressedKeys = Object.keys(thisPadsLastPressed);%0A                        // if was not pressed last event%0A                        if(lastPressedKeys.indexOf(idx.toString()) %3C 0)%0A                            gamePadCallback(pad, idx, %22pressed%22);%0A                    %7D else %7B%0A                        // if was never pressed before
 %0A   
@@ -1682,32 +1682,54 @@
 dx, %22pressed%22);%0A
+                    %7D%0A
                 
@@ -1944,32 +1944,74 @@
             %7D);%0A
+            if (pressed != undefined)%0A    
             last

fix gamepad input exception