const Phaser = require('phaser');


const HomeCryps = require('./home.cryps');
const HomeNavigation = require('./home.navigation');

const HomeRankings = require('./home.rankings');
const HomeNews = require('./home.news');
const HomeShop = require('./home.shop');
const HomeInstances = require('./home.instances');

const FIXED_SCENES = [
    'HomeCryps',
    'HomeNavigation',
];

const VAR_SCENES = [
    'HomeRankings',
    'HomeNews',
    'HomeShop',
    'HomeInstances',
];

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

    create() {
        this.registry.get('ws').sendAccountPlayers();

        this.registry.events.on('changedata', this.updateData, this);
        this.registry.events.on('setdata', this.updateData, this);
        this.scene.manager.add('HomeCryps', HomeCryps, true);
        this.scene.manager.add('HomeNavigation', HomeNavigation, true);


        return true;
    }

    updateData(parent, key, data) {
        if (!data) return false;
        // Controls which scene shows in the main top right section
        switch (key) {
            case 'game': return this.cleanUp();
            case 'menu': return this.cleanUp();
            case 'homeInstances': return this.newMainScene('HomeInstances', HomeInstances, data);
            case 'homeRankings': return this.newMainScene('HomeRankings', HomeRankings, data);
            case 'homeNews': return this.newMainScene('HomeNews', HomeNews, data);
            case 'homeShop': return this.newMainScene('HomeShop', HomeShop, data);


            default: return false;
        }
    }

    newMainScene(key, scene, data) {
        let addScene = true;
        // List of scenes which could be occupying the main section of the menu
        VAR_SCENES.forEach((sKey) => {
            if (this.scene.manager.keys[sKey]) {
                if (key === sKey) {
                    // If there is new data for the current scene restart
                    this.scene.manager.keys[sKey].scene.restart(data);
                    addScene = false;
                } else {
                    // Delete the old scene
                    this.scene.manager.keys[sKey].cleanUp();
                }
            }
        });
        if (addScene) this.scene.manager.add(key, scene, true, data);
    }

    cleanUp() {
        this.registry.events.off('changedata', this.updateData, this);
        this.registry.events.off('setdata', this.updateData, this);
        // Delete scenes which could be showing before switching to battle scene

        const removeScenes = (sKey) => {
            if (this.scene.get(sKey)) this.scene.get(sKey).cleanUp();
        };
        FIXED_SCENES.forEach(removeScenes);
        VAR_SCENES.forEach(removeScenes);


        this.scene.remove();
    }
}

module.exports = Home;
