const _keyboard_controller_bindings = {};
const _binding_types = {
    Up: "Up",
    Down: "Down",
    Hold: "Hold",
};
const _keyboard_current_states = {};

window.addEventListener("keydown", (event) => {
    _keyboard_current_states[event.code] = true;
    // console.log(event.code);
});

window.addEventListener("keyup", (event) => {
    _keyboard_current_states[event.code] = false;
});

/**
 *
 * @param {String} key
 * @param {_binding_types} type
 * @param {Array} event
 */
export function createKeyboardBinding(key, type, events) {

    if(_keyboard_controller_bindings[key] !== undefined)
    {
        _keyboard_controller_bindings[key] = [..._keyboard_controller_bindings[key], {
            type: type,
            events: [..._keyboard_controller_bindings[key].events, ...events],
            triggered: _keyboard_controller_bindings[key].triggered,
        }];
    }
    else
    {
        _keyboard_controller_bindings[key] = [{
            type,
            events: [...events],
            triggered: false,
        }];
    }
}

export function inputControllerTick(deltaTime) {
    for (const binding in _keyboard_controller_bindings) {
        let bind0 = _keyboard_controller_bindings[binding];
        if(_keyboard_current_states[binding] === undefined) continue;
        for (const bind of bind0) {
            if(bind.type === "Hold" && _keyboard_current_states[binding])
            {
                for (const i of bind.events) {
                    i(deltaTime, binding);
                }
            }
            else if ((bind.type === "Down" && !bind.triggered && _keyboard_current_states[binding]) ||
                        (bind.type === "Up" && !bind.triggered && !_keyboard_current_states[binding]))
            {
                for (const i of bind.events) {
                    i(deltaTime, binding);
                }
                bind.triggered = true;
            }
            else if ((bind.type === "Down" && bind.triggered && !_keyboard_current_states[binding]) ||
                        (bind.type === "Up" && bind.triggered && _keyboard_current_states[binding]))
            {
                bind.triggered = false;
            }
        }
    }
}
