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

    preload ()
    {
        this.load.image("fgWin10", "assets/10_free_games.png?ver=" + VERSION);
        this.load.image("fgWin15", "assets/15_free_games.png?ver=" + VERSION);
        this.load.image("fgWin25", "assets/25_free_games.png?ver=" + VERSION);

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

        this.load.audio("fgShot", "assets/sound/fgshot.mp3?ver=" + VERSION);
        this.load.audio("fgOut", "assets/sound/fgout.mp3?ver=" + VERSION);

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

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

    }

    create (data)
    {
        this.parentScene = data.scene;

        this.container = this.add.container(0, 0).setVisible(false);
//landscape
        this.leftDoor = this.add.image(-1430, -50, "shojil").setInteractive();
        this.leftDoor.on("pointerup", this.playFreeGames, this);

        this.container.add(this.leftDoor);

//landscape
        this.rightDoor = this.add.image(1450, -50, "shojil").setFlipX(true).setInteractive();
        this.rightDoor.on("pointerup", this.playFreeGames, this);

        this.container.add(this.rightDoor);

        this.fgWin10 = this.add.image(7, 85, "fgWin10").setVisible(false);

        this.container.add(this.fgWin10);

        this.fgWin15 = this.add.image(7, 85, "fgWin15").setVisible(false);

        this.container.add(this.fgWin15);

        this.fgWin25 = this.add.image(7, 85, "fgWin25").setVisible(false);

        this.container.add(this.fgWin25);

        this.taptostart = this.add.image(0, 0, "taptostart").setVisible(false);

        this.container.add(this.fgWin25);

        this.fgOut = this.add.image(7, -252, "fgOut").setVisible(false);

        this.container.add(this.fgOut);

        this.freeGamesWin = 0;

        this.doorsMoved = 0;

        this.doorsState = DOORS_STATE_NONE;

        this.fgClickEnabled = false;

        this.winCounter = new AnimatedAmount2(this, 0, 0, { fontFamily: "Arial", fontSize: 60, fontStyle: "bold", color: "#ffffff" }, false);
        this.winCounter.setOrigin(0.5).setVisible(false).setScale(1.0).reset(1);

//entry scene        
        this.bmNmFreeGames = this.add.bitmapText(0, 0, "winFont", "").setOrigin(0.5).setScale(1.0).setVisible(false).setLetterSpacing(-60);

        this.bmTxtFree = this.add.bitmapText(0, 0, "winFont", "FREE").setOrigin(0.5).setScale(1.0).setVisible(false).setLetterSpacing(-20);

        this.bmTxtGames = this.add.bitmapText(0, 0, "winFont", "GAMES").setOrigin(0.5).setScale(1.0).setVisible(false).setLetterSpacing(-65);

//free game play

        this.bmTxtFreeGames = this.add.bitmapText(0, 0, "winFont", "FREE GAMES").setOrigin(0.5).setLetterSpacing(-55).setVisible(false);

        this.bmTxtCurrentFreeGame = this.add.bitmapText(0, 0, "winFont", "").setOrigin(0.5).setLetterSpacing(-20).setVisible(false);

// free games end

        this.totalFreeGames = 0;
        this.currentFreeGame = 1;

        let loopFGEntryMarker = {
            name: "loopFGEntry",
            start: 0,
            duration: 7.994,
            config: {
                loop: true
            }
        };


        this.sndFreeGamesEntry = this.sound.add("fgEntry");
        this.sndFreeGamesEntry.addMarker(loopFGEntryMarker);

        this.sndFreeGamesOut = this.sound.add("fgOut", { loop: false });
        this.sndFreeGamesOut.on("complete", this.sndFreeGamesOutComplete, this);

        this.leftDoorTween = null;
        this.rightDoorTween = null;

        this.freeGamesTween = null;
        this.currentFreeGameTween = null;

        this.scene.sleep();
    }

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

        if (status < Phaser.Scenes.RUNNING)
        {
            return;
        }

        if (this.parentScene.isLandscapeMode ())
        {
            this.container.setPosition(950, 590);

            this.bmNmFreeGames.setPosition(970, 500);
            this.bmTxtFree.setPosition(970, 700);
            this.bmTxtGames.setPosition(970, 900 );

            this.taptostart.setPosition(960, 1060);
            
            this.winCounter.setPosition(960, 1010);

            this.leftDoor.setTexture("shojil");
            this.rightDoor.setTexture("shojil");

            if (this.leftDoorTween == null)
            {
                this.leftDoor.setPosition(-1430, -50);
                this.rightDoor.setPosition(1450, -50);
            }
            else
            {
                this.leftDoor.setPosition(-470, -50);
                this.rightDoor.setPosition(490, -50);
            }
            
            this.fgWin10.setPosition(7, -85).setScale(0.9);
            this.fgWin15.setPosition(7, -85).setScale(0.9);
            this.fgWin25.setPosition(7, -85).setScale(0.9);
        }
        else
        {
            this.container.setPosition(536, 930);

            this.bmNmFreeGames.setPosition(530, 840);
            this.bmTxtFree.setPosition(530, 1040);
            this.bmTxtGames.setPosition(530, 1240 );

            this.taptostart.setPosition(540, 1560);

            this.winCounter.setPosition(540, 1850);

            this.leftDoor.setTexture("shojip");
            this.rightDoor.setTexture("shojip");

            if (this.leftDoorTween == null)
            {
                this.leftDoor.setPosition(-806, 28);
                this.rightDoor.setPosition(814, 28);
            }
            else
            {
                this.leftDoor.setPosition(-266, 28);
                this.rightDoor.setPosition(274, 28);
            }

            this.fgWin10.setPosition(7, 85).setScale(1.0);
            this.fgWin15.setPosition(7, 85).setScale(1.0);
            this.fgWin25.setPosition(7, 85).setScale(1.0);
        }
        
        if (this.doorsState == DOORS_STATE_START_CLOSING || this.doorsState == DOORS_STATE_END_CLOSING)
        {
            this.leftDoorTween = this.updateDoorTween("left", this.leftDoorTween, true);
            this.rightDoorTween = this.updateDoorTween("right", this.rightDoorTween, true);
        }
        else if (this.doorsState == DOORS_STATE_START_OPENING || this.doorsState == DOORS_STATE_END_OPENING)
        {
            this.leftDoorTween = this.updateDoorTween("left", this.leftDoorTween, false);
            this.rightDoorTween = this.updateDoorTween("right", this.rightDoorTween, false);
        }

        this.freeGamesTween = this.updateTween(this.freeGamesTween, this.bmTxtFreeGames, 960, 507, 960, 507, 507, 0.5, false);
        this.currentFreeGameTween = this.updateTween(this.currentFreeGameTween, this.bmTxtCurrentFreeGame, 960, 657, 960, 657, 707, 0.65, false);
    }

    updateTween(tween, object, x, y, x1, y1, ty, scale, visible)
    {
        let isLandscape = this.parentScene.isLandscapeMode();
        let isPlaying = tween?.isPlaying();

        if (!isPlaying)
        {
            let [targetX, targetY] = (tween == null) ? [x, y] : [x1, y1];
            
            object.setPosition(
                isLandscape ? targetX : targetX - 420,
                isLandscape ? targetY : targetY + 336
            );
        } 
        else
        {
            object.setPosition(
                isLandscape ? object.x + 420 : object.x - 420,
                isLandscape ? object.y - 336 : object.y + 336
            );

            let finalTy = isLandscape ? ty : ty + 336;

            tween = this.createTween(tween, object, finalTy, scale, visible);
        }

        return tween;
    }

    createTween(tween, object, ty, scale, visible)
    {
        tween.stop();

        return this.tweens.add({
            targets: object,
            ease: "Linear",
            duration: tween.totalDuration - tween.totalElapsed,
            y: ty,
            scale: scale,
            onCallbackScope: this,
            onComplete: function ()
            {
                object.setVisible(visible);
            }
        });
    }
    
    updateDoorTween(side, tween, isOpen)
    {
        let isLeft = side === "left";
        let door = isLeft ? this.leftDoor : this.rightDoor;
        let isLandscape = this.parentScene.isLandscapeMode();

        let tx = isOpen 
            ? (isLandscape ? (isLeft ? -470 : 490) : (isLeft ? -266 : 274))
            : (isLandscape ? (isLeft ? -1430 : 1450) : (isLeft ? -806 : 814));

        let ty = isLandscape ? -50 : 28;
        let texture = isLandscape ? "shojil" : "shojip";
        let offset = isLandscape ? 960 : 540;
        
        let direction = isOpen ? (isLeft ? -1 : 1) : (isLeft ? 1 : -1);

        door.y = ty;
        door.setTexture(texture);

        if (tween == null || !tween.isPlaying())
        {
            let dx = (tween == null) ? (direction * offset) : 0;
            door.setPosition(tx + dx, ty);
        } 
        else
        {
            tween.stop();

            let duration = tween.totalDuration;
            let elapsed = tween.totalElapsed;
            let progress = 1 - (elapsed / duration);

            door.x = tx + (direction * offset * progress);

            tween = this.tweens.add({
                targets: door,
                ease: "Linear",
                duration: duration - elapsed,
                x: tx,
                callbackScope: this,
                onComplete: function ()
                {
                    this.moveDoorsComplete()
                }
            });
        }

        return tween;
    }

    bringToTop ()
    {
        this.scene.bringToTop();
    }

    reset ()
    {
        this.totalFreeGames = 0;
        this.currentFreeGame = 1;
        this.freeGamesWin = 0;
        this.doorsMoved = 0;

        this.fgClickEnabled = false;

        this.container.setVisible(false);

        this.winCounter.setVisible(false).setScale(1.0).reset(1);        

        this.bmNmFreeGames.setVisible(false);
        this.bmTxtFree.setVisible(false);
        this.bmTxtGames.setVisible(false);

        this.freeGamesTween = null;
        this.currentFreeGameTween = null;

        this.sleep();
    }

    update (time, delta)
    {
        this.winCounter.update(delta, this.freeGamesWin);
    }

    updateFreeGamesWin (v)
    {
        this.freeGamesWin += v;

        if (this.parentScene.gameSocket.spinInfo.legalLimitApplied && this.freeGamesWin > this.parentScene.gameSocket.spinInfo.win)//check if legal limit win is reached (when present)
        {
            this.freeGamesWin = this.parentScene.gameSocket.spinInfo.win;
        }

        if (!this.winCounter.visible)
        {
            this.setWinCounterVisible(true);
        }

        this.animateWin();
    }

    setWinCounterVisible (v)
    {
        this.winCounter.setVisible(v);
    }

    setPrecision (v)
    {
        this.winCounter.setPrecision(v);
    }

    animateWin ()
    {
        this.tweens.add({

            targets: this.winCounter.txText,
            ease: "Linear",
            duration: 1000,
            scaleX: 1.3,
            scaleY: 1.3,

            callbackScope: this,
            onComplete: function() 
            {
                this.winCounter.setScale (1.0);
            },
        });
    }

    wake ()
    {
        this.scene.wake();
        this.scene.bringToTop();
    }

    sleep ()
    {
        this.scene.sleep();
    }

    playFreeGamesEntry (sc)
    {
        this.sc = sc;
        
        this.scene.wake();
        this.scene.bringToTop();

        let fg;

        switch (sc)
        {
            case 3: {fg = 10;};break;
            case 4: {fg = 15;};break;
            case 5: {fg = 25;};break;
        }

        if (this.totalFreeGames == 0)
        {
            this.container.setVisible(true);
            
            this.totalFreeGames = fg;

            this.sndFreeGamesEntry.play("loopFGEntry", {delay: 0});

            this.closeDoors(DOORS_STATE_START_CLOSING);
        }
        else
        {
            this.playNmFreeGames(fg);
        }
    }

    moveDoorsComplete ()
    {
        if (++this.doorsMoved == 2)
        {
            this.doorsMoved = 0;

            if (this.doorsState == DOORS_STATE_START_CLOSING)
            {
                switch (this.sc)
                {
                    case 3: {this.fgWin10.setVisible(true);};break;
                    case 4: {this.fgWin15.setVisible(true);};break;
                    case 5: {this.fgWin25.setVisible(true);};break;
                }

                this.taptostart.setVisible(true);

                this.fgClickEnabled = true;
            }
            else if (this.doorsState == DOORS_STATE_START_OPENING)
            {
                this.container.setVisible(false);

                this.leftDoorTween = null;
                this.rightDoorTween = null;

                this.fgClickEnabled = false;
                
                this.parentScene.playFreeGame();
            }
            else if (this.doorsState == DOORS_STATE_END_CLOSING)
            {
                this.fgOut.setVisible(true);
            }
            else if (this.doorsState == DOORS_STATE_END_OPENING)
            {
                this.parentScene.tw.setRepeat(0);//signal tw scene that end music is complete and go forward
            }

            this.doorsState = DOORS_STATE_NONE;
        }
    }

    closeDoors (state)
    {
        this.doorsState = state;

        let tx1, tx2;

        if (this.parentScene.isLandscapeMode() )
        {
            tx1 = -470;
            tx2 = 490;
        }
        else
        {
            tx1 = -266;
            tx2 = 274;
        }

        this.leftDoorTween = this.tweens.add({

            targets: this.leftDoor,
            ease: "Linear",
            duration: 1000,

            x: tx1,

            callbackScope: this,
            onComplete: function() 
            {
                this.moveDoorsComplete();
            },
        });

        this.rightDoorTween = this.tweens.add({

            targets: this.rightDoor,
            ease: "Linear",
            duration: 1000,

            x: tx2,

            callbackScope: this,
            onComplete: function() 
            {
                this.moveDoorsComplete();
            },
        });
    }

    openDoors (state)
    {
        if (state == DOORS_STATE_START_OPENING)
        {
            switch (this.sc)
            {
                case 3: {this.fgWin10.setVisible(false);};break;
                case 4: {this.fgWin15.setVisible(false);};break;
                case 5: {this.fgWin25.setVisible(false);};break;
            }

            this.taptostart.setVisible(false);

            this.sndFreeGamesEntry.stop();
        }
        else if (state == DOORS_STATE_END_OPENING)
        {
            this.fgOut.setVisible(false);
        }
        
        this.doorsState = state;

        let tx1, tx2;

        if (this.parentScene.isLandscapeMode() )
        {
            tx1 = -1430;
            tx2 = 1450;
        }
        else
        {
            tx1 = -806;
            tx2 = 814;
        }

        this.leftDoorTween = this.tweens.add({

            targets: this.leftDoor,
            ease: "Linear",
            duration: 1000,

            x: tx1,

            callbackScope: this,
            onComplete: function() 
            {
                this.moveDoorsComplete();
            },
        });

        this.rightDoorTween = this.tweens.add({

            targets: this.rightDoor,
            ease: "Linear",
            duration: 1000,

            x: tx2,

            callbackScope: this,
            onComplete: function() 
            {
                this.moveDoorsComplete();
            },
        });
    }

    playFreeGames ()
    {
        if (!this.fgClickEnabled)
        {
            return;
        }
        
        this.openDoors(DOORS_STATE_START_OPENING);
    }

    playNmFreeGames (fg)
    {
        this.wake();

        this.totalFreeGames += fg;
        this.bmNmFreeGames.setText(fg).setVisible(true);

        this.sound.play("fgShot");

        this.time.delayedCall(1000, this.playTxtFree, [], this);
    }

    playTxtFree ()
    {
        this.bmTxtFree.setVisible(true);

        this.sound.play("fgShot");

        this.time.delayedCall(1000, this.playTxtGames, [], this);
    }

    playTxtGames ()
    {
        this.bmTxtGames.setVisible(true);

        this.sound.play("fgShot");

        this.time.delayedCall(1000, this.showFreeFreeGamesWonComplete, [], this);
    }

    showFreeFreeGamesWonComplete ()
    {
        this.bmNmFreeGames.setVisible(false);
        this.bmTxtFree.setVisible(false);
        this.bmTxtGames.setVisible(false);

        this.parentScene.playFreeGame();
    }

//play free game N of M
    freeGameStart ()
    {
        this.scene.wake();
        this.scene.bringToTop();

        this.showFreeGamesMsg();
        this.showCurrentFreeGame();
    }

    showFreeGamesMsg ()
    {
        this.bmTxtFreeGames.setVisible(true);
        
        let duration = 1000;

        let dx = 0;
        let dy = 0;

        if (this.parentScene.isPortraitMode() )
        {
            dx = -420;
            dy = 336;
        }

        if (!this.parentScene.isFastSpin())
        {
            this.bmTxtFreeGames.setPosition(960 + dx, 507 + dy).setScale(0.23);
        }
        else
        {
            this.bmTxtFreeGames.setPosition(960 + dx, 507 + dy).setScale(0.5);

            duration = 300;
        }

        this.freeGamesTween = this.tweens.add({

            targets: this.bmTxtFreeGames,
            ease: "Linear",
            duration: duration,

            y: 507 + dy,
            scale: 0.5,

            callbackScope: this,
            onComplete: function() 
            {
                this.bmTxtFreeGames.setVisible(false);
            },
        });
    }

    showCurrentFreeGame ()
    {
        this.bmTxtCurrentFreeGame.setText(this.currentFreeGame++ + " OF " + this.totalFreeGames).setVisible(true);

        let duration = 1000;

        let dx = 0;
        let dy = 0;

        if (this.parentScene.isPortraitMode() )
        {
            dx = -420;
            dy = 336;
        }

        if (!this.parentScene.isFastSpin())
        {
            this.bmTxtCurrentFreeGame.setPosition(960 + dx, 657 + dy).setScale(0.39);
        }
        else
        {
            this.bmTxtCurrentFreeGame.setPosition(960 + dx, 707 + dy).setScale(0.65);

            duration = 300;
        }

        this.currentFreeGameTween = this.tweens.add({

            targets: this.bmTxtCurrentFreeGame,
            ease: "Linear",
            duration: duration,

            y: 707 + dy,

            scale: 0.65,
 
            callbackScope: this,
            onComplete: function() 
            {
                this.bmTxtCurrentFreeGame.setVisible(false);
            },
        });
    }

    showFreeGamesWin ()
    {
        this.scene.wake();
        this.scene.bringToTop();

        if (this.freeGamesWin > 0)
        {
            this.sndFreeGamesOut.play();

            this.container.setVisible(true);

            this.closeDoors (DOORS_STATE_END_CLOSING);
        }

        this.parentScene.showFreeGamesWin(this.freeGamesWin);
    }

    sndFreeGamesOutComplete ()
    {
        this.openDoors (DOORS_STATE_END_OPENING);
    }
}
