class SceneLobby extends Phaser.Scene {

    constructor ()
    {
        super({ key: 'Lobby', active: true });
        this.console = new Console();
        this.console.enable();

        this.page = 1;
        this.nmpages = 1;

        this.icons = [];

        this.ippLandscape = 15;
        this.ippPortrait = 10;
        
        this.balancePollTime = 20000;
        this.balancePollTimer = -1;

        this.timerRes = -1;
        this.waitForGameListTime = 10000;
        this.waitForGameListTimer = -1;
    }
    
    preload()
    {
        this.load.image('overlay', 'assets/overlay.png');
        
        this.load.image('dotw', '../common/assets/dotw.png');
        this.load.image('dotb', '../common/assets/dotb.png');

        this.load.audio("click", "assets/sound/lbclick.mp3");
		
        this.load.spritesheet("homeBtn", "../common/assets/home.png",{ frameWidth: 131, frameHeight: 131 });
        this.load.spritesheet("prevBtn", "../common/assets/prev.png",{ frameWidth: 72, frameHeight: 77 });
        this.load.spritesheet("nextBtn", "../common/assets/next.png",{ frameWidth: 72, frameHeight: 77 });

        this.load.bitmapFont('barLetters', '../common/fonts/bar_letters.png', '../common/fonts/bar_letters.xml');
	}

    create(data)
    {
        this.add.image(640, 360, 'overlay');

        this.games = null;

        this.gameSocket = data.gameSocket;
        this.server = data.Hostname;
        this.port = data.Port;
        this.token = data.WalletToken;
        this.gameid = data.gameId;
        this.userid = data.userId;
        this.casinoid = data.casinoId;
        this.lobbyUrl = data.lobbyUrl;

        this.modeLandscape = data.modeLandscape;

        this.rt = this.add.renderTexture(0, 0, 80, 16);

        this.rt.setOrigin(0);

        this.homeUrl = "";

        this.gameSocket.send_cmd_get_games();

        if(this.modeLandscape)
        {
            this.vDelta = 0;
        }
        else
        {
            this.vDelta = 800;
        }

        let config = this.cache.json.get('config').casinoUrls;

        if(this.lobbyUrl != null && this.lobbyUrl != "")
        {
            this.homeUrl = this.lobbyUrl;
        }
        else
        {
            if(config != null)
            {
                for(let i = 0; i < config.length; ++i)
                {
                    if(parseInt(config[i].casinoId) === parseInt(this.casinoid))
                    {
                        this.homeUrl = config[i].url;
                        break;
                    }
                }
            }
        }
            
        fetch('../assets/games.json', {credentials: 'omit'})
            .then(response =>
            {
                if (!response.ok)
                {
                    throw new Error('Invalid response');
                }
                
                return response.json();
            })
            .then(data =>
            {
                this.data = data;
               
                this.waitForGameListTimer = this.waitForGameListTime;
                this.timerRes = setInterval(this.waitForGameList.bind(this), 100);

                return;
            })
            .catch(error =>
            {
                console.error('Fetch operation failed:', error);
            });

        this.keyOrientation = this.input.keyboard.addKey('P');
        this.keyOrientation.on('down', this.onKbdOrientation, this);

        this.scene.remove("HomeBtn");
        this.scene.remove("Start");

        window.addEventListener("orientationchange", this.onOrientationChange.bind(this), false);
    }

    onOrientationChange(event)
    {
        let orientation = 0;

        if(window.hasOwnProperty('orientation'))
        {
            orientation = window.orientation;
        }
        else if(window.screen.orientation.hasOwnProperty('angle'))
        {
            orientation = window.screen.orientation.angle;
        }
        else
        {
            return;
        }
        
        if (orientation == 0 || orientation == 180)
        {
            this.setPortraitLayout();
        }
        else if (orientation == 90 || orientation == -90 || orientation == 270)
        {
            this.setLandscapeLayout();
        }
    }

    waitForGameList()
    {
        let protocols = this.gameSocket.getGameProtocols();
        
        if(protocols.length > 0 || this.waitForGameListTimer < 0)
        {
            clearInterval(this.timerRes);
            this.timerRes = -1;
            this.createIcons();
        }
    }

    createIcons()
    {
        let protocols = this.gameSocket.getGameProtocols();
        let games = [];
        
        for(let i = 0; i < this.data.games.length; ++i)
        {
            if(protocols.length == 0)
            {
                this.load.spritesheet(this.data.games[i]["name"], this.data.baseUrl + this.data.games[i]["icon"],{ frameWidth: 220, frameHeight: 145 });
            }
            else if(protocols.includes(this.data.games[i]["name"]))
            {
                games.push(this.data.games[i]);
                this.load.spritesheet(this.data.games[i]["name"], this.data.baseUrl + this.data.games[i]["icon"],{ frameWidth: 220, frameHeight: 145 });
            }                
        }

        if(games.length > 0)
        {
            this.data.games = games;
        }            

        this.nmfiles = 0;

        this.load.start();
    
        this.load.on('fileprogress', this.progressFn, this);
    
        this.load.on('complete', function ()
        {
            for(let i = 0; i < this.data.games.length; ++i)
            {
                let data = {
                    'scene': this,
                    'key': this.data.games[i]["name"],
                    'gameid': this.data.games[i]["id"],
                    'url': this.data.games[i]["url"],
                    'frameWidth':220,
                    'frameHeight':145,
                    'x': 0,
                    'y': 0,
                    'horizontalOffset': 0,
                    'vDelta': 0,
                    'onClick': this.onStart,
                    'onPressed': null
                }
    
                let icon = this.scene.add(this.data.games[i]["name"], SceneIcon, true, data);

                this.icons.push(icon);
            }

            let homeBtnData = {
                'scene': this,
                'key':'homeBtn',
                'frameWidth':182,
                'frameHeight':183,
                'x': 70,
                'y': 670,
                'horizontalOffset': 0,
                'vDelta': 0,
                'onClick': this.onHome,
                'onPressed': null
            };
    
            this.homeBtn = this.scene.add("HomeBtn", SceneButton, true, homeBtnData);

            let prevBtnData = {
                'scene': this,
                'key':'prevBtn',
                'frameWidth':72,
                'frameHeight':77,
                'x': 395,
                'y': 675,
                'horizontalOffset': 0,
                'vDelta': 0,
                'onClick': this.prevPage,
                'onPressed': null
            }
    
            this.prevBtn = this.scene.add("PrevBtn", SceneButton, true, prevBtnData);
    
            let nextBtnData = {
                'scene': this,
                'key':'nextBtn',
                'frameWidth':72,
                'frameHeight':77,
                'x': 885,
                'y': 675,
                'horizontalOffset': 0,
                'vDelta': 0,
                'onClick': this.nextPage,
                'onPressed': null
            }
    
            this.nextBtn = this.scene.add("NextBtn", SceneButton, true, nextBtnData);

            if(this.homeUrl !== "")
            {
                this.homeBtn.scene.wake();
                this.homeBtn.scene.bringToTop();
                this.homeBtn.setScale(0.7);
            }
                
            this.prevBtn.scene.wake();
            this.prevBtn.scene.bringToTop();
    
            this.nextBtn.scene.wake();
            this.nextBtn.scene.bringToTop();

            this.bar = this.scene.add("LobbyBar", LobbyBar, true, {scene: this, key: 'bgrbar', vDelta: this.vDelta, fontBet: "fontBet", fontUnits: "fontUnits"});
            this.bar.scene.wake();
            this.bar.scene.bringToTop();

            this.balancePollTimer = this.balancePollTime;

            this.bar.updateBalance(this.gameSocket.getBalance());

            if (!this.modeLandscape)
            {
                this.setPortraitLayout();
            }
            else
            {
                this.setLandscapeLayout();
            }

            this.showIcons();

        },this);

        return true;
    }

    onHome()
    {
        if(this.homeUrl != "")
        {
            parent.location.href = this.homeUrl;
        }
    }

    onStart(url, gameid)
    {
        let data = {
                        'Hostname': this.server,
                        'Port': this.port,
                        'WalletToken': this.token,
                        'gameId': gameid,
                        'userId': this.userid,
                        'casinoId': this.casinoid
                   };

         this.post(this.data.baseUrl + url, data);
    }

    post(path, params, method = 'post')
    {
        const form = document.createElement('form');
        form.method = method;
        form.action = path;
      
        for (const key in params)
        {
            if (params.hasOwnProperty(key))
            {
                const hiddenField = document.createElement('input');
                hiddenField.type = 'hidden';
                hiddenField.name = key;
                hiddenField.value = params[key];
                form.appendChild(hiddenField);
            }
        }
      
        document.body.appendChild(form);
        form.submit();
      }

    progressFn(file, value)
    {
    };

    showIcons()
    {
        if(this.icons.length == 0)
        {
            return;
        }
        
        this.icons.forEach(icon => {icon.scene.sleep();});
        
        if(this.modeLandscape)
        {
            this.showIconsLandscape();
        }
        else
        {
            this.showIconsPortrait();
        }
    }

    showIconsLandscape()
    {
        let items = ((this.page * this.ippLandscape) < this.icons.length)?this.page * this.ippLandscape:this.icons.length;

        for(let i = (this.page - 1) * this.ippLandscape; i < items; ++i)
        {
            let j = i % 5;
            let k = Math.floor((i - (this.page - 1) * this.ippLandscape) / 5);
           
            let x = 140 + (250) * j;
            let y = 112 + 190 * k;

            this.icons[i].setPosition(x, y);
            this.icons[i].scene.wake();
            this.icons[i].scene.bringToTop();
        }

        this.rt.clear();

        let w = this.nmpages * 32;

        let centerx = Math.floor((1280 - w) / 2);

        this.rt.setPosition(centerx, 595);
        this.rt.setSize(w, 16);

        for(let i = 0; i < this.nmpages; ++i)
        {
            if((i + 1) == this.page)
            {
                this.rt.draw('dotw', i * 32, 0);
            }
            else
            {
                this.rt.draw('dotb', i * 32, 0);
            }                
        }
    }

    showIconsPortrait()
    {
        let items = ((this.page * this.ippPortrait) < this.icons.length)?this.page * this.ippPortrait:this.icons.length;

        for(let i = (this.page - 1) * this.ippPortrait; i < items; ++i)
        {
            let j = i % 2;
            let k = Math.floor((i - (this.page - 1) * this.ippPortrait) / 2);
           
            let x = 360 + 550 * j;
            let y = 240 + 340 * k;

            this.icons[i].setPosition(x, y);
            this.icons[i].scene.wake();
            this.icons[i].scene.bringToTop();
        }

        this.rt.clear();

        let w = this.nmpages * 32;

        let centerx = Math.floor((1280 - w) / 2);

        this.rt.setPosition(centerx, 1000 + this.vDelta);
        this.rt.setSize(w, 16);

        for(let i = 0; i < this.nmpages; ++i)
        {
            if((i + 1) == this.page)
            {
                this.rt.draw('dotw', i * 32, 0);
            }
            else
            {
                this.rt.draw('dotb', i * 32, 0);
            }                
        }
    }

    prevPage()
    {
        if(this.page > 1)
        {
            --this.page;
        }

        if(this.page <= 1)
        {
            this.prevBtn.disable();
        }
        else
        {
            this.prevBtn.enable();
        }
        if(this.page >= this.nmpages)
        {
            this.nextBtn.disable();
        }
        else
        {
            this.nextBtn.enable();
        }

        this.showIcons();
    }

    nextPage()
    {
        if(this.page < this.nmpages)
        {
            ++this.page;
        }

        if(this.page <= 1)
        {
            this.prevBtn.disable();
        }
        else
        {
            this.prevBtn.enable();
        }

        if(this.page >= this.nmpages)
        {
            this.nextBtn.disable();
        }
        else
        {
            this.nextBtn.enable();
        }

        this.showIcons();
    }

    onKbdOrientation()
    {
        if(this.modeLandscape)
        {
            this.setPortraitLayout();
        }
        else
        {
            this.setLandscapeLayout();
        }
    }

    setLandscapeLayout()
    {
        this.scale.orientation = Phaser.Scale.LANDSCAPE;
        this.scale.setGameSize(GAME_WIDTH, GAME_LANDSCAPE_HEIGHT);
        this.scale.displaySize.resize(GAME_WIDTH, GAME_LANDSCAPE_HEIGHT);
        this.scale.parentSize.setSize(this.scale.canvasBounds.width, this.scale.canvasBounds.height);
        this.scale.displaySize.setAspectRatio(this.scale.baseSize.aspectRatio);

        this.vDelta = 0;
        this.page = 1;

        this.homeBtn.setPosition(70, 670 + this.vDelta);
        this.homeBtn.setScale(0.7);

        this.prevBtn.setPosition(395, 675 + this.vDelta);
        this.nextBtn.setPosition(855, 675 + this.vDelta );

        this.prevBtn.setScale(1.0);
        this.nextBtn.setScale(1.0);

        this.icons.forEach(icon => {icon.setScale(1.0);});

        this.nmpages = Math.floor((this.icons.length + this.ippLandscape - 1)/ this.ippLandscape);

        this.prevBtn.disable();

        if(this.nmpages == 1)
        {
            this.nextBtn.disable();
        }
        else
        {
            this.nextBtn.enable();
        }    

        this.modeLandscape = true;
        this.showIcons();
        
        this.bar.onOrientationChange(this.vDelta);
    }
    
    setPortraitLayout()
    {
        this.scale.orientation = Phaser.Scale.PORTRAIT;
        this.scale.setGameSize(GAME_WIDTH, GAME_PORTRAIT_HEIGHT);
        this.scale.displaySize.resize(GAME_WIDTH, GAME_PORTRAIT_HEIGHT);
        this.scale.parentSize.setSize(this.scale.canvasBounds.width, this.scale.canvasBounds.height);
        this.scale.displaySize.setAspectRatio(this.scale.baseSize.aspectRatio);

        this.vDelta = 800;
        this.page = 1;

        this.homeBtn.setPosition(630, 1270 + this.vDelta);
        this.homeBtn.setScale(1.0);

        this.prevBtn.setPosition(195, 1140 + this.vDelta);
        this.nextBtn.setPosition(1085, 1140 + this.vDelta );

        this.prevBtn.setScale(2.0);
        this.nextBtn.setScale(2.0);

        this.icons.forEach(icon => {icon.setScale(2.0);});

        this.nmpages = Math.floor((this.icons.length + this.ippPortrait - 1)/ this.ippPortrait);

        this.prevBtn.disable();

        if(this.nmpages == 1)
        {
            this.nextBtn.disable();
        }
        else
        {
            this.nextBtn.enable();
        }    


        this.modeLandscape = false;
        this.showIcons();

        this.bar.onOrientationChange(this.vDelta);
    }

    update(time, delta) 
    {
        if(this.waitForGameListTimer >= 0)
        {
            this.waitForGameListTimer -= delta;
        }

        if(this.balancePollTimer >= 0)
        {
            this.balancePollTimer -= delta;

            if(this.balancePollTimer < 0)
            {
                this.gameSocket.queryBalance();
                this.bar.updateBalance(this.gameSocket.getBalance());
                this.balancePollTimer = this.balancePollTime;
            }
        }
    }
}
