// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import GameData from "./GameData";
import SoundManager from "./SoundsManager";

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Label)
    scoreLabel: cc.Label = null;

    @property(cc.Node)
    flashOverlay: cc.Node = null;

    explisionEnabled: boolean = false;
    isOnCooldown: boolean = false;

    onLoad() {
        if (!this.scoreLabel) {
            this.scoreLabel = cc.find("Canvas/ScoreBox/ScoreLabel").getComponent(cc.Label);
        }
        if (this.flashOverlay) {
            this.flashOverlay.opacity = 0;
        }
    }

    explode() {
        if (!this.explisionEnabled || this.isOnCooldown) return;

        this.flashOverlay.runAction(cc.fadeTo(0.25, 100));
        
        if (this.flashOverlay) {
            this.scheduleOnce(() => {
                SoundManager.instance.playEffect('LoudExplosion');
                this.flashOverlay.stopAllActions();
                this.flashOverlay.runAction(cc.fadeOut(1));

                const enemies = this.node.parent.children.filter(n => n.getComponent("EnemyShip"));
                GameData.instance.setScore(GameData.instance.getScore() - 100);
                this.scoreLabel.string = (parseInt(this.scoreLabel.string) - 100).toString();

                enemies.forEach(enemy => {
                    enemy.getComponent(cc.Collider).enabled = false;
                    enemy.stopAllActions();
                    enemy.getComponent(cc.Animation).play();
                });
            }, 0.5);
        }

        this.isOnCooldown = true;
        this.node.opacity = 50;
        this.scheduleOnce(() => {
            this.isOnCooldown = false;
        }, 30);
    }

    update(dt) {
        if (parseInt(this.scoreLabel.string) > 100 && !this.isOnCooldown) {
            this.explisionEnabled = true;
            this.node.opacity = 255;
        } else {
            this.explisionEnabled = false;
            this.node.opacity = 50;
        }
    }
}
