class SceneStart extends Phaser.Scene 
{
    constructor ()
    {
        super({ key: "SceneStart", active: true });

        this.console = new Console();
        this.console.enable();

        document.getElementById("game").style.backgroundColor = "#000000";
    }
    
    preload ()
    {
        this.load.audio("click", "../common/assets/sound/common/click.mp3?ver=" + VERSION);

        this.load.image("logointrol", "assets/logointrol.png?ver=" + VERSION);
        this.load.image("logointrop", "assets/logointrop.png?ver=" + VERSION);

        this.load.image("bgrbackl", "assets/bgrbackl.png?ver=" + VERSION);
        this.load.image("bgrbackp", "assets/bgrbackp.png?ver=" + VERSION);

        this.load.spritesheet("loading", "../common/assets/loadingyellow.png?ver=" + VERSION, { frameWidth: 744, frameHeight: 27 });

        this.load.json("config", "../config.json?ver=" + VERSION);
        
        this.load.scenePlugin({key: "rexgesturesplugin", url: "../common/js/swipeplugin.js?ver=" + VERSION, sceneKey: "gestures"});
        this.load.scenePlugin({key: "rexuiplugin", url: "../common/js/uiplugin.js?ver=" + VERSION, sceneKey: "rexui" });
	}

    create ()
    {
        let config = this.cache.json.get("config");

        let languages = [];

        if (config.hasOwnProperty("languages"))
        {
            languages = config.languages;
        }
        
        let lang = "en";//default

        if (config.hasOwnProperty("lang"))
        {
            lang = config.lang[0];
        }

        if (localStorage)
        {
            if (localStorage.lang) 
            { 
                let e = languages.find(function (element)
                {
                    return element.lang == localStorage.lang;
                }, this);

                if (e != undefined)
                {
                    lang = localStorage.lang;
                }    
            };
        }

        fetch("../common/assets/lang/" + lang + "/texts.txt", {credentials: "omit"})
            .then(response =>
            {
                if (!response.ok)
                {
                    lang = "en";
                }
                
                this.loadResources(config, lang, languages);
            })
            .catch(error =>
            {
                this.loadResources(config, "en", languages);
            });
    }

    loadResources (config, lang, languages)
    {
        localStorage.setItem("lang", lang);

        let forceLandscapeMode = 0;

        if (config.hasOwnProperty("forceLandscapeModeOnDesktop"))
        {
            forceLandscapeMode = config.forceLandscapeModeOnDesktop | 0;
        }

        this.bgrintrol = this.add.image(960, 540, "bgrbackl").setVisible(false);
        this.bgrintrop = this.add.image(540, 960, "bgrbackp").setVisible(false);

        this.logointrol = this.add.image(982, 480, "logointrol").setVisible(false);
        this.logointrop = this.add.image(558, 970, "logointrop").setVisible(false);

        this.loading = this.add.image(640, 630, "loading");
        
        this.scene.bringToTop("SceneStart");

        this.orientationLandscape = true;

        if (forceLandscapeMode)
        {
            this.orientationLandscape = true;
        }

        this.setOrientation();
       
        this.keyLayout = this.input.keyboard.addKey("P");
        this.keyLayout.on("down", this.onChangeLayout, this);

        if (screen.orientation && screen.orientation.addEventListener)
        {
            screen.orientation.addEventListener("change", this.setOrientation.bind(this), false);
        }
        else
        {
            window.addEventListener("orientationchange", this.setOrientation.bind(this), false);
        }

        this.load.text("globalTexts", "../common/assets/lang/" + lang + "/texts.txt?ver=" + VERSION);
        this.load.text("localTexts", "assets/lang/" + lang + "/texts.txt?ver=" + VERSION);

        this.load.image("bgrreels", "assets/bgrreels.png?ver=" + VERSION);

        this.load.image("barp", "../common/assets/barp.png?ver=" + VERSION);
        this.load.image("logol", "assets/logol.png?ver=" + VERSION);
        this.load.image("logop", "assets/logop.png?ver=" + VERSION);
        this.load.image("logosmall", "assets/logosmall.png?ver=" + VERSION);
        this.load.image("overlay", "../common/assets/overlay.png?ver=" + VERSION);
        this.load.image("unlimited", "../common/assets/unlimited.png?ver=" + VERSION);
        this.load.image("arrowsUpDown", "../common/assets/arrows_up_down.png?ver=" + VERSION);
        this.load.image("jackpotLock", "../common/assets/jackpot_lock.png?ver=" + VERSION);
        this.load.image("bonusl", "../common/assets/bonus_l.png?ver=" + VERSION);
        this.load.image("bonusp", "../common/assets/bonus_p.png?ver=" + VERSION);

        this.load.image("plate", "assets/plate.png");

        this.load.bitmapFont("winFont", "assets/fonts/winfont.png?ver=" + VERSION, "assets/fonts/winfont.xml?ver=" + VERSION);
        this.load.bitmapFont("fontLegalLimitWin", "../common/fonts/legal_limit_win.png?ver=" + VERSION, "../common/fonts/legal_limit_win.xml?ver=" + VERSION);

        this.load.spritesheet("spinBtn", "../common/assets/spin.png?ver=" + VERSION,{ frameWidth: 264, frameHeight: 264 });
        this.load.spritesheet("betBtn", "../common/assets/bet.png?ver=" + VERSION,{ frameWidth: 162, frameHeight: 161 });
        this.load.spritesheet("collectBtn", "../common/assets/collect.png?ver=" + VERSION,{ frameWidth: 162, frameHeight: 161 });
        this.load.spritesheet("connectBtn", "../common/assets/connect.png?ver=" + VERSION,{ frameWidth: 264, frameHeight: 264 });
        this.load.spritesheet("takeBtn", "../common/assets/take.png?ver=" + VERSION,{ frameWidth: 264, frameHeight: 264 });
        this.load.spritesheet("stopBtn", "../common/assets/stop.png?ver=" + VERSION,{ frameWidth: 264, frameHeight: 264 });
        this.load.spritesheet("autoPlayBtn", "../common/assets/auto_play.png?ver=" + VERSION,{ frameWidth: 162, frameHeight: 161 });
        this.load.spritesheet("autoStopBtn", "../common/assets/auto_stop.png?ver=" + VERSION,{ frameWidth: 264, frameHeight: 264 });
        this.load.spritesheet("autoStopCounterBtn", "../common/assets/auto_stop_counter.png?ver=" + VERSION,{ frameWidth: 264, frameHeight: 264 });
        this.load.spritesheet("settingsBtn", "../common/assets/settings.png?ver=" + VERSION,{ frameWidth: 162, frameHeight: 161 });
        this.load.spritesheet("homeBtn", "../common/assets/home.png?ver=" + VERSION,{ frameWidth: 94, frameHeight: 94 });
        this.load.spritesheet("soundBtn", "../common/assets/sound.png?ver=" + VERSION,{ frameWidth: 94, frameHeight: 94 });
        this.load.spritesheet("soundOffBtn", "../common/assets/sound_off.png?ver=" + VERSION,{ frameWidth: 94, frameHeight: 94 });

        this.load.spritesheet("turboOnOffBtn", "../common/assets/turbo_on_off.png?ver=" + VERSION,{ frameWidth: 224, frameHeight: 98 });

        this.load.spritesheet("lobbyBtn", "../common/assets/lobby.png?ver=" + VERSION, { frameWidth: 216, frameHeight: 152 });

        this.load.spritesheet("stars", "../common/assets/stars.png?ver=" + VERSION, { frameWidth: 60, frameHeight: 60 });

        this.load.image("coin", "../common/assets/coin.png?ver=" + VERSION);
        
        this.load.spritesheet("coin1", "../common/assets/coin1.png?ver=" + VERSION, { frameWidth: 300, frameHeight: 300 });
        this.load.spritesheet("coin2", "../common/assets/coin2.png?ver=" + VERSION, { frameWidth: 300, frameHeight: 300 });

        this.load.audio("stop", "../common/assets/sound/sounds1/stop.mp3?ver=" + VERSION);

        this.load.audio("faststop", "../common/assets/sound/sounds1/faststop.mp3?ver=" + VERSION);

        this.load.audio("wild1", "../common/assets/sound/sounds1/wild1.mp3?ver=" + VERSION);
        this.load.audio("wild2", "../common/assets/sound/sounds1/wild2.mp3?ver=" + VERSION);
        this.load.audio("wild3", "../common/assets/sound/sounds1/wild3.mp3?ver=" + VERSION);
        this.load.audio("wild4", "../common/assets/sound/sounds1/wild4.mp3?ver=" + VERSION);

        this.load.audio("scatter1", "../common/assets/sound/sounds1/scatter1.mp3?ver=" + VERSION);
        this.load.audio("scatter2", "../common/assets/sound/sounds1/scatter2.mp3?ver=" + VERSION);
        this.load.audio("scatter3", "../common/assets/sound/sounds1/scatter3.mp3?ver=" + VERSION);
        this.load.audio("scatter4", "../common/assets/sound/sounds1/scatter4.mp3?ver=" + VERSION);
        this.load.audio("scatter5", "../common/assets/sound/sounds1/scatter5.mp3?ver=" + VERSION);

        this.load.audio("spin", "assets/sound/spin.mp3?ver=" + VERSION);
        this.load.audio("spinFG", "assets/sound/spinfg.mp3?ver=" + VERSION);
        this.load.audio("win", "assets/sound/win.mp3?ver=" + VERSION);
        this.load.audio("bonusWin", "../common/assets/sound/common/bonus_win.mp3?ver=" + VERSION);
        this.load.audio("winToCredit", "../common/assets/sound/common/win_to_credit.mp3?ver=" + VERSION);
        this.load.audio("winToCreditEnd", "../common/assets/sound/common/win_to_credit_end.mp3?ver=" + VERSION);
        this.load.audio("credit", "../common/assets/sound/common/credit.mp3?ver=" + VERSION);

        this.load.audio("applause", "assets/sound/applause.mp3?ver=" + VERSION);
        this.load.audio("fgEntry", "assets/sound/fgentry.mp3?ver=" + VERSION);
        this.load.audio("fgMark", "assets/sound/fgmark.mp3?ver=" + VERSION);

        this.load.audio("longMV", "assets/sound/longmovement.mp3?ver=" + VERSION);
        this.load.audio("longMVS", "assets/sound/longmovementstart.mp3?ver=" + VERSION);

        this.load.image("fgBonus", "./assets/free_games.png?ver=" + VERSION);
        this.load.image("garland", "./assets/garland.png?ver=" + VERSION);

        this.load.spritesheet("ten", "assets/reels/10.png?ver=" + VERSION,{ frameWidth: 176, frameHeight: 174 });
        this.load.spritesheet("jack", "assets/reels/J.png?ver=" + VERSION,{ frameWidth: 163, frameHeight: 155 });
        this.load.spritesheet("queen", "assets/reels/Q.png?ver=" + VERSION,{ frameWidth: 163, frameHeight: 168 });
        this.load.spritesheet("king", "assets/reels/K.png?ver=" + VERSION,{ frameWidth: 164, frameHeight: 170 });
        this.load.spritesheet("ace", "assets/reels/A.png?ver=" + VERSION,{ frameWidth: 173, frameHeight: 173 });
        this.load.atlas("leg", "assets/reels/leg.png?ver=" + VERSION, "assets/reels/leg.json?ver=" + VERSION);
        this.load.atlas("knee", "assets/reels/knee.png?ver=" + VERSION, "assets/reels/knee.json?ver=" + VERSION);
        this.load.spritesheet("elbow", "assets/reels/elbow.png?ver=" + VERSION,{ frameWidth: 264, frameHeight: 269 });
        this.load.spritesheet("hand", "assets/reels/hand.png?ver=" + VERSION,{ frameWidth: 264, frameHeight: 250 });
        this.load.spritesheet("warrior", "assets/reels/warrior.png?ver=" + VERSION,{ frameWidth: 196, frameHeight: 212 });
        this.load.atlas("wild", "assets/reels/wild.png?ver=" + VERSION, "assets/reels/wild.json?ver=" + VERSION);
        this.load.atlas("scatter", "assets/reels/scatter.png?ver=" + VERSION, "assets/reels/scatter.json?ver=" + VERSION);

        this.load.atlas("scatterAnim", "assets/scatteranim.png?ver=" + VERSION, "assets/scatteranim.json?ver=" + VERSION);

        this.load.image("bgrstrip1l", "./assets/bgrstrip1l.png?ver=" + VERSION);
        this.load.image("bgrstrip2l", "./assets/bgrstrip2l.png?ver=" + VERSION);
        this.load.image("bgrstrip1p", "./assets/bgrstrip1p.png?ver=" + VERSION);
        this.load.image("bgrstrip2p", "./assets/bgrstrip2p.png?ver=" + VERSION);

        this.nmfiles = 0;

        this.load.start();
        
        this.load.on("fileprogress", this.progressFn, this);
    
        this.load.on("complete", function ()
        {
            let globalTexts = new Map();

            let m = this.cache.text.get("globalTexts");

            if (m != undefined)
            {
                let lines = m.split("\n");

                for (let i = 0; i < lines.length; ++i)
                {
                    lines[i] = lines[i].replace(/(\r\n|\n|\r)/gm, "");
                    let line = lines[i].split("::");

                    globalTexts.set(parseInt(line[0]), line[1]);
                }
            }

            let localTexts = new Map();

            m = this.cache.text.get("localTexts");

            if (m != undefined)
            {
                let lines = m.split("\n");

                for (let i = 0; i < lines.length; ++i)
                {
                    lines[i] = lines[i].replace(/(\r\n|\n|\r)/gm, "");
                    let line = lines[i].split("::");

                    localTexts.set(parseInt(line[0]), line[1]);
                }
            }
            
            this.main = this.scene.add("SceneMain", SceneMain, false, {config: config,
                                                                       lang: lang,
                                                                       languages: languages,
                                                                       globalTexts: globalTexts,
                                                                       localTexts: localTexts});

            this.main.start(this);

            this.introMsg = this.add.text(900, 700, globalTexts.get(GLOBAL_TXT_INTRO_MESSAGE), { fontFamily: "Arial", fontSize: 54, fontStyle: "bold", color: "#ffffff" }).setOrigin(0.5);
            this.introMsg.setVisible(false);

            let sndBtnData = {
                "scene": this,
                "key": "soundBtn",
                "onClick": this.startWithSound,
                "onPressed": null,
                "onSwipe": null
            };

            this.sndIntroBtn = this.scene.add("SoundIntroBtn", SceneButton, true, sndBtnData);
            this.sndIntroBtn.setScale(2.3);

            let sndOffBtnData = {
                "scene": this,
                "key": "soundOffBtn",
                "onClick": this.startNoSound,
                "onPressed": null,
                "onSwipe": null
            };

            this.sndIntroOffBtn = this.scene.add("SoundIntroOffBtn", SceneButton, true, sndOffBtnData);
            this.sndIntroOffBtn.setScale(2.3);

        },this);
    }

    onChangeLayout()
    {
        let status = this.scene.getStatus(this.scene.key);

        if (status == Phaser.Scenes.SHUTDOWN)
        {
            return;
        }

        if (!this.orientationLandscape)
        {
            this.scale.orientation = Phaser.Scale.PORTRAIT;
            this.scale.setGameSize(GAME_PORTRAIT_WIDTH, GAME_PORTRAIT_HEIGHT);

            this.bgrintrol.setVisible(false);
            this.bgrintrop.setVisible(true);

            this.logointrol.setVisible(false);
            this.logointrop.setVisible(true);

            this.loading.setPosition(540, 1680);
            this.loading.setScale(1.0, 1.5);

            if (this.hasOwnProperty("introMsg"))
            {
                this.introMsg.setPosition(540, 1800);
            }

            if (this.hasOwnProperty("sndIntroBtn"))
            {
                this.sndIntroBtn.setPosition(690, 1618);
                this.sndIntroBtn.setScale(2.3);
                this.sndIntroOffBtn.setPosition(382, 1618);
                this.sndIntroOffBtn.setScale(2.3);
            }

            if (this.hasOwnProperty("main"))
            {
                this.main.error.onOrientationChange();
            }
        }
        else
        {
            this.scale.orientation = Phaser.Scale.LANDSCAPE;
            this.scale.setGameSize(GAME_LANDSCAPE_WIDTH, GAME_LANDSCAPE_HEIGHT);

            this.bgrintrol.setVisible(true);
            this.bgrintrop.setVisible(false);

            this.logointrol.setVisible(true);
            this.logointrop.setVisible(false);

            this.loading.setPosition(960, 930);
            this.loading.setScale(1.0);

            if (this.hasOwnProperty("introMsg"))
            {
                this.introMsg.setPosition(960, 1030);
            }

            if (this.hasOwnProperty("sndIntroBtn"))
            {
                this.sndIntroBtn.setPosition(1080, 900);
                this.sndIntroBtn.setScale(2.0);
                this.sndIntroOffBtn.setPosition(840, 900);
                this.sndIntroOffBtn.setScale(2.0);
            }

            if (this.hasOwnProperty("main"))
            {
                this.main.error.onOrientationChange();
            }
        }

        this.orientationLandscape = !this.orientationLandscape;
    }

    progressFn (file, value)
    {
        if (value == 1)
        {
            ++this.nmfiles;

            let v = this.nmfiles / 90;

            v = (v > 1.0)?1.0:v;

            this.loading.setFrame(Math.round(v * /*13*/12));
        }
    }

    clear ()
    {
        if (screen.orientation && screen.orientation.addEventListener)
        {
            screen.orientation.removeEventListener("change", this.setOrientation, false);
        }
        else
        {
            window.removeEventListener("orientationchange", this.setOrientation, false);
        }

        this.keyLayout.off("down", this.onChangeLayout, this);

        if (this.hasOwnProperty("sndIntroBtn"))
        {
            this.sndIntroBtn.sleep();
        }

        if (this.hasOwnProperty("sndIntroOffBtn"))
        {
            this.sndIntroOffBtn.sleep();
        }

        if (this.hasOwnProperty("introMsg"))
        {
            this.introMsg.setVisible(false);
        }
    }

    waitScenesToLoad ()
    {
        let scenes = this.scene.manager.getScenes(false);

        for (let i = 0; i < scenes.length; ++i)
        {
            if (scenes[i].scene.getStatus(scenes[i].scene.key) < Phaser.Scenes.RUNNING)
            {
                this.time.delayedCall(300, this.waitScenesToLoad, [], this);
                
                return;
            }
        }

        this.loading.setFrame(13);

        this.time.delayedCall(300, this.readyToStart, [], this);
    }

    readyToStart ()
    {
        this.loading.setVisible(false);

        if (this.main.errorPending)
        {
            this.sndIntroBtn.sleep();
            this.sndIntroOffBtn.sleep();

            this.introMsg.setVisible(false);
            
            this.main.error.setMessage(this.main.errorMessage, this.main.errorWalletMessage, this.main.errorExtraMessage);
            this.main.error.scene.bringToTop();

            return;
        }

        this.introMsg.setVisible(true);

        this.sndIntroBtn.wake();
        this.sndIntroOffBtn.wake();

        if (this.scale.orientation === "landscape" || this.scale.orientation === "landscape-primary" || this.scale.orientation === "landscape-secondary")
        {
            this.sndIntroBtn.setPosition(1080, 900);
            this.sndIntroBtn.setScale(2.0);
            this.sndIntroOffBtn.setPosition(840, 900);
            this.sndIntroOffBtn.setScale(2.0);

            this.introMsg.setPosition(960, 1030);
        }
        else
        {
            this.sndIntroBtn.setPosition(690, 1618);
            this.sndIntroBtn.setScale(2.3);
            this.sndIntroOffBtn.setPosition(382, 1618);
            this.sndIntroOffBtn.setScale(2.3);

            this.introMsg.setPosition(540, 1800);
        }
    }

    startNoSound ()
    {
        this.sound.setMute(true);
        this.start();
    }

    startWithSound ()
    {
        this.sound.setMute(false);
        this.start();
    }

    start ()
    {
        this.clear();

        this.introMsg.destroy();

        if (this.main.criticalError)
        {
            return;
        }

        if (!this.sys.game.device.os.desktop && this.sys.game.device.fullscreen.available)
        {
            this.scale.on("fullscreenunsupported", function() {console.log("fullscreen not supported");});
            this.scale.on("fullscreenfailed", function() {console.log("fullscreen failed");});
            this.scale.on("enterfullscreen", function() {console.log("entered fullscreen");});
            this.scale.startFullscreen();
        }

        this.main.startSceneComplete();
    }

    setOrientation ()
    {
        let orientation = null;

        if (screen.orientation.hasOwnProperty("angle"))
        {
            orientation = screen.orientation.angle;
        }
        else if (window.hasOwnProperty("orientation"))
        {
            orientation = window.orientation;
        }

        if (orientation !== null)
        {
            if (orientation == 0 || orientation == 180)
            {
                this.orientationLandscape = false;
            }
            else if (orientation == 90 || orientation == -90 || orientation == 270)
            {
                this.orientationLandscape = true;
            }
        }

        this.onChangeLayout();
    }    

    update (time, delta) 
    {
    }
}

let config = 
{
    type: Phaser.AUTO,
    width: GAME_LANDSCAPE_WIDTH,
    height: GAME_LANDSCAPE_HEIGHT,
    scale: 
    {
        mode: Phaser.Scale.FIT,
        autoCenter: Phaser.Scale.CENTER_BOTH,
        fullscreenTarget: "game"
    },

    min: 20,
    target: 60,
    forceSetTimeOut: true,

    deltaHistory: 30,

    parent: "game",
    transparent: true,
    scene: [ SceneStart ]
};


let game = new Phaser.Game(config);
