#include rng.js

const OsuKeys = (function() {
    const urlBase = '//static.flash.moe/sounds/';
    const rng = new MamiRNG;
    let sndRng = false;

    const playSound = function(name) {
        if(!mami.hasSound())
            return;

        const urls = {
            ogg: urlBase + name + '.ogg',
            mp3: urlBase + name + '.mp3',
        };

        mami.getSound().load('OsuKeys:' + name, urls, function(success, buffer) {
            if(success) {
                const source = buffer.createSource();
                if(sndRng)
                    source.setRate(1.8 - (rng.sample() * 1.5));
                source.play();
            }
        });
    };

    const playPress   = function() { playSound('key-press-' + rng.next(1, 5).toString()); };
    const playCaps    = function() { playSound('key-caps'); };
    const playConfirm = function() { playSound('key-confirm'); };
    const playDelete  = function() { playSound('key-delete'); };
    const playMove    = function() { playSound('key-movement'); };

    const keyHandler = function(ev) {
        switch(ev.key) {
            case 'Enter':
            case 'NumpadEnter':
                playConfirm();
                break;
            case 'Backspace':
            case 'Delete':
                playDelete();
                break;
            case 'NumLock':
            case 'CapsLock':
            case 'ScrollLock':
                playCaps();
                break;
            case 'ArrowUp':
            case 'ArrowDown':
            case 'ArrowLeft':
            case 'ArrowRight':
                playMove();
                break;
            case 'Control':
            case 'Alt':
            case 'Shift':
                break;
            default:
                playPress();
                break;
        }
    };

    return {
        playConfirm: playConfirm,
        playDelete: playDelete,
        playCaps: playCaps,
        playMove: playMove,
        playPress: playPress,
        setEnable: function(value) {
            if(value)
                window.addEventListener('keydown', keyHandler);
            else
                window.removeEventListener('keydown', keyHandler);
        },
        setRandomRate: function(value) { sndRng = !!value; },
    };
})();
