import { RomPatcher } from './RomPatcher.js';

window.PlayOnline = function( initialPatches = {}, emulatorJsConfig = {} ){

    const parent = RomPatcher( initialPatches );

    return {

        ...parent,

        currentBlobUrl: null,
        emuConfig: emulatorJsConfig,
        launchGame: false,

        init(){
            parent.init({
                language: 'en',
                requireValidation: false,
                onpatch: this.handlePatchedRomFile.bind(this),
            });
        },

        cleanEmulatorJsVars() {
            ['EJS_player','EJS_core','EJS_gameUrl','EJS_pathtodata',
               'EJS_startOnLoaded','EJS_threads']
                .forEach(k => delete window[k]);
        },

        prepareEmulatorJs(){
            window.EJS_player = '#game';
            window.EJS_core = this.emuConfig.core;
            window.EJS_gameUrl = this.currentBlobUrl;
            window.EJS_pathtodata = "https://cdn.emulatorjs.org/stable/data/";
            window.EJS_startOnLoaded = true;
            window.EJS_threads = this.emuConfig.threads ?? false;
        },

        launchEmulatorJs(){
            if(!this.currentBlobUrl){
                console.error("EmulatorJS: Empty Blob field");
                return;
            }

            console.log(this.currentBlobUrl);

            this.cleanEmulatorJsVars();
            this.prepareEmulatorJs();

            const script   = document.createElement('script');
            script.id      = 'ejs-loader';
            script.src     = 'https://cdn.emulatorjs.org/stable/data/loader.js';
            document.body.appendChild(script);

            this.launchGame = true;

        },

        /**
         * @param {BinFile} patchedRomFile
         */
        handlePatchedRomFile( patchedRomFile ){

            patchedRomFile.save = function(){
                // Remove save.
                return;
            }

            const u8 = patchedRomFile._u8array;
            if( !u8 || u8.byteLength === 0 ){
                console.error("Patch error: Empty ROM file");
                return;
            }

            if(this.currentBlobUrl){
                URL.revokeObjectURL(this.currentBlobUrl);
            }

            const blob = new Blob([u8], { type: 'application/octet-stream' });
            this.currentBlobUrl = URL.createObjectURL(blob);

            this.launchEmulatorJs()
        }
    }

}
