import wait from "../../libs/new_tc/wait";
import MovieClip from "../physics/movieclip/MovieClip";

const playMovieClip = async (parent: egret.DisplayObjectContainer, key, frames, frameInterval = 5) => {
    return new Promise(async (r) => {
        let texture: egret.SpriteSheet;
        texture = RES.getRes(key);
        if (texture) {
            await createMc(parent, texture, frames, frameInterval);
            r(1);
        }
        else {
            RES.getResAsync(key);
            wait(300).then(async () => {
                texture = RES.getRes(key);
                if (texture) {
                    await createMc(parent, texture, frames, frameInterval);
                    r(1);
                } else
                    r(0);
            })
        }
    });
}

const createMc = (parent: egret.DisplayObjectContainer, spritesheet: egret.SpriteSheet, frames: any[], frameInterval = 5) => {
    return new Promise((r) => {
        const movieclip = new MovieClip({
            spritesheet: spritesheet,
            frameInterval: frameInterval,
            frames: frames,
            position: [0, 0],
            scale: 1,
            anchor: [0, 0],
            loop: false
        });
        parent.addChild(movieclip);
        movieclip.once(egret.Event.COMPLETE, () => {
            parent.removeChild(movieclip);
            r(1)
        }, this)
    })
}

export const playSuccess = (parent) => {
    return playMovieClip(parent, 'success_json', ['1', '2', '3', '4', '5', '6', '7', '8', '9'], 5);
}

export const playBoom = (parent) => {
    return playMovieClip(parent, 'fail_json', ['1', '2', '3', '4', '5', '6', '7', '8'], 5);
}

export const playScoreAni = (parent, score: number) => {
    const txt = createText(score);
    txt.scaleX = txt.scaleY = 0;
    parent.addChild(txt);
    txt.x = 375 + 100;
    txt.y = 375;
    txt.anchorOffsetX = txt.textWidth / 2;
    txt.anchorOffsetY = txt.textHeight / 2;
    egret.Tween.get(txt).to({ scaleX: 1, scaleY: 1 }, 300, egret.Ease.getBackOut(6)).wait(500)
        .to({ y: txt.y - 100, alpha: 0 }, 700).call(() => {

        })
}

const createText = (score: number) => {
    const txt = new egret.TextField();
    txt.size = 40;
    txt.bold = true;
    const prefix = score > 0 ? '+' : '';
    txt.text = prefix + score;
    txt.textColor = score > 0 ? 0x00ff00 : 0xff0000;
    return txt;
}