// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import Game from "../../scene/Game";
import pg from "../../scene/pg";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MouseStart extends cc.Component {
    @property(cc.Vec2)
    startPosition: cc.Vec2 = cc.v2(0, 0)
    @property(cc.Vec2)
    targetPosition: cc.Vec2 = cc.v2(0, 0)
    @property(cc.Float)
    moveInTime: number = 1;

    private ske: cc.Node;
    private block: cc.Node;
    onLoad() {
        //修改ske的信息
        this.ske = this.node.getChildByName("ske");
        this.block = this.node.getChildByName("block");
        this.ske.x = this.startPosition.x;
        this.ske.y = this.startPosition.y;
    }
    play(audioUrl?: string) {
        this.moveInTime = Game.getIns().aniEnter.time || 5;
        return new Promise((resolve, reject) => {
            let isPlaying = true;
            this.ske.x = this.startPosition.x;
            this.ske.y = this.startPosition.y;
            this.ske.active = true;
            this.node.active = true;
            this.block.active = true;
            pg.load.loadDB(this.ske, { ske: Game.getIns().aniEnter.skeJsonData.url, tex: Game.getIns().aniEnter.texJsonData.url, png: Game.getIns().aniEnter.texPngData.url }).then((animationName) => {
                cc.tween(this.ske).to(1.3, { x: this.targetPosition.x, y: this.targetPosition.y }).call(() => {
                    audioUrl = audioUrl ? audioUrl : Game.getIns().aniEnter.audioUrl;
                    if (audioUrl) {
                        pg.audio.playAudioByUrl(audioUrl).then(() => {
                            isPlaying = false;
                            resolve('');
                        })
                    }
                    let db = this.ske.getComponent(dragonBones.ArmatureDisplay);
                    db.playAnimation('normal', 1111111);
                    db.addEventListener("loopComplete", () => {
                        if (!isPlaying) {
                            this.block.active = false;
                            resolve('');
                        }
                    })
                }).delay(this.moveInTime).call(() => {
                    this.ske.active = false;
                    this.node.active = false;
                    this.block.active = false;
                }).start();
            })
        });
    }
}
