import game, { GlobalData } from "..";
let disableInputTimer;

export default class InputHelper {
    private title: string;
    private value: string;
    private created: boolean;
    private browser: BrowserMp;
    private data: IGlobalData;

    constructor(title: string, globalData?: IGlobalData) {
        this.title = title;
        this.data = globalData || GlobalData;

        this.cefTitleCall = this.cefTitleCall.bind(this);
        mp.events.add('cef_request_title', this.cefTitleCall);

        this.cefCallback = this.cefCallback.bind(this);
        mp.events.add('cef_inputhelper_sendvalue', this.cefCallback);

        this.finish = this.finish.bind(this);
        this.show = this.show.bind(this);
        this.valueGetter = this.valueGetter.bind(this);
        this.getValue = this.getValue.bind(this);

        this.value = undefined;

        mp.events.add('closeinputhelper', this.finish);
    }

    show() {
        if (this.created) return;       
        this.data.InMenu = true;
        this.created = true;
        this.browser = mp.browsers.new('package://assets/html/inputhelper/index.html');
        mp.gui.cursor.show(true, true);
        disableInputTimer = setInterval(disableInput, 1);
    }

    private finish() {
        if (this.browser) {
            clearInterval(disableInputTimer);
            mp.events.remove('cef_inputhelper_sendvalue');
            mp.events.remove('cef_request_title');
            mp.events.remove('closeinputhelper');
            this.browser.destroy();
            this.data.InMenu = false;
            this.created = false;
            this.browser = null;
            mp.gui.cursor.show(false, false);
            
        }
    }

    private cefTitleCall() {
        this.browser.execute(`setTitle('${this.title}')`);
    }

    private cefCallback(val) {
        this.value = val;
        this.finish();
    }

    private valueGetter(): Promise<string> {
        return new Promise(resolve => {
            while (this.value === undefined) {
                mp.game.wait(1);
            }
            resolve(this.value);
        });
    }
    async getValue(callback: Function) {
        var getVal = await this.valueGetter();
        callback(getVal);
    }       
}

function disableInput() {
    for (var x = 0; x < 32; x++) {
        mp.game.controls.disableAllControlActions(x);
    }
}

exports = InputHelper;