class GamingBoard extends Phaser.Scene {
    constructor(father) {
        super('GamingBoard');
        this.listRobot = [];
        listBonus = [];
        this.father = father;
        this.end = false;
    }

    preload() {
        this.cameras.main.setViewport(OFFX_MAP, OFFY_MAP, WIDTH_MAP, WIDTH_MAP);
        this.sound.add('shot');
        this.sound.add('hit');
    }

    create() {
        listBonus.push(new BonusSpeed('Fusée', this, WIDTH_MAP / 2, WIDTH_MAP / 2, 5, 2000));

        this.add.image(0, 0, 'background').alpha = 0.1;

        for (let i = 0; i < this.listRobot.length; i++) {
            this.listRobot[i].setTarget(chooseTarget(this.listRobot[i], this.listRobot));
        }

        this.listRobot[0].drawRange();

        this.time.addEvent({delay: 2000, callback: this.upShield, callbackScope: this});

    }

    update(time, delta) {
        super.update(time, delta);
        this.listRobot.forEach(function (robot) {
            robot.read();
        })

        for (let i = 0; i < this.listRobot.length; i++) {
            if (!this.listRobot[i].isAlive()) {
                this.listRobot.splice(i, 1);
                i -= 1;
            } else {
                if (!this.listRobot[i].haveTarget()) {
                    this.listRobot[i].setTarget(chooseTarget(this.listRobot[i], this.listRobot));
                }
            }
        }

        if (this.listRobot.length <= 1 && !this.end) {
            this.end = true;
            this.finish();
        }
    }

    finish() {
        this.pause();
        this.father.finish();
    }

    winner() {
        return this.getMyRobot() !== undefined;
    }

    pause() {
        this.scene.pause('GamingBoard');
        this.sound.pauseAll();
    }

    resume() {
        this.scene.resume('GamingBoard');
        this.sound.resumeAll();
    }

    addRobot(robot) {
        this.listRobot.push(robot);
    }

    modifyNodes(lNodes) {
        let myRobot = this.getMyRobot();
        if (myRobot !== undefined) {
            myRobot.cleanNodes();
            lNodes.forEach(element => myRobot.addNode(element));
            return true;
        }
        return false;
    }

    modifyValue(damage, speedReload, speed, range) {
        let myRobot = this.getMyRobot();
        if (myRobot !== undefined) {
            myRobot.setSpeed(speed);
            myRobot.setRange(range);
            myRobot.setSpeedReload(speedReload);
            myRobot.setDamage(damage);
            return true;
        }
        return false;
    }

    getMyRobot() {
        for (let i = 0; i < this.listRobot.length; i++) {
            if (this.listRobot[i].name === MYSELF) {
                return this.listRobot[i];
            }
        }
        return undefined;
    }


    upShield() {
        this.listRobot.forEach(robot => robot.addShield(SHIELD_PER_SECOND));
        this.time.addEvent({delay: 1000 / SPEED_GAME, callback: this.upShield, callbackScope: this});
    }

}