class LevelSelect extends ManageLang {
    constructor(father, level = "") {
        super('LevelSelect');
        this.father = father;
        this.level = level;
    }

    create() {
        super.create();
        let style = {font: HEIGHT_TITLE.toString() + 'px stencil', fill: "#e2e2e2"};
        this.add.text(WIDTH_WINDOW / 2, HEIGHT_WINDOW / 6, "WARIA", style).setOrigin(0.5, 0.5);
        let nb = parseInt(getCookie(this.level));
        if (isNaN(nb)) {
            nb = 1;
        }
        let offX = WIDTH_WINDOW / 5;
        let offY = HEIGHT_WINDOW / 3;
        let x = offX;
        let y = HEIGHT_WINDOW / 2.5;
        for (let i = 1; i <= nb; i++) {
            if (i > NUMBER_LEVEL)
                break;
            this.createLevel(x, y, i);
            x += offX;
            if (x === WIDTH_WINDOW) {
                x = offX;
                y += offY;
            }
        }

        new Button(this, 10, 10, WIDTH_BUTTON, WIDTH_BUTTON, 'back', () => this.clickBack()).setOrigin(0, 0);
    }

    createLevel(x, y, number = 0) {
        let width;
        if (WIDTH_WINDOW > HEIGHT_WINDOW * 1.3) {
            width = HEIGHT_WINDOW / 4;
        } else {
            width = WIDTH_WINDOW / 6;
        }
        let btn = this.add.image(x, y, 'rectangle').setOrigin(0.5, 0.5).setInteractive();
        btn.displayHeight = btn.displayWidth = width;
        let style = {font: (width / 2).toString() + 'px stencil', fill: "#000000", align: "center"};
        let text = this.add.text(x, y, number.toString(), style).setOrigin(0.5, 0.5);

        let score = parseInt(getCookie(this.level + (number - 1).toString()));
        let scoreText;

        if (!isNaN(score)) {
            scoreText = this.add.text(x, text.y + text.displayHeight / 2, selectWord("RECORD SCORE :", "SCORE RECORD :") + "\n" + score.toString(), style).setOrigin(0.5, 0);
            if (scoreText.displayWidth > width * 0.9) {
                scoreText.displayWidth = width * 0.9;
                scoreText.scaleY = scoreText.scaleX;
            }
        }

        btn.on('pointerover', () => this.over(btn, text, scoreText));
        btn.on('pointerout', () => this.out(btn, text, scoreText));
        btn.on('pointerdown', () => this.click(number));
    }

    over(btn, ...texts) {
        btn.setFrame(1);
        texts.forEach(text => {
            if (text !== undefined)
                text.setColor("white");
        });
    }

    out(btn, ...texts) {
        btn.setFrame(0);
        texts.forEach(text => {
            if (text !== undefined)
                text.setColor("black");
        });
    }

    click(number) {
        number -= 1;
        this.level += number.toString();
        newGame(this.father, this.level);
        this.scene.start('Game');
    }

    clickBack() {
        this.scene.start('Type');
    }
}