
import MovieClip from "../physics/MovieClip";
import wait from "./wait";
import { getJosnData, getJsonAsset } from "./JsonTools";
import { createTextureSheet } from "./createTextureSheet";
import { getTextureByName } from "./utils";

export async function playMovieClip (parent: engine.Container, key, frames, frameInterval = 5){
    return new Promise(async (r) => {
        let josnData = getJosnData(key);
        if(!josnData){
            getJsonAsset(key);
            josnData = getJosnData(key);
        }
        let texture =  createTextureSheet(getTextureByName(key).baseTexture,josnData);
        if (texture) {
            await createMc(parent, texture, frames, frameInterval);
            r(1);
        }
        else {
            //RES.getResAsync(key);
            wait(300).then(async () => {
                let josnData = getJosnData(key);
                if(!josnData){
                    getJsonAsset(key);
                    josnData = getJosnData(key);
                }
                texture =  createTextureSheet(getTextureByName(key).baseTexture,josnData);
                if (texture) {
                    await createMc(parent, texture, frames, frameInterval);
                    r(1);
                } else
                    r(0);
            })
        }
    });
}
export  function createMc(parent: engine.Container, spritesheet, frames: any[], frameInterval = 5) {
    return new Promise((r) => {

        const movieclip = new MovieClip({
            spritesheet: spritesheet,
            frameInterval: frameInterval,
            frames: frames,
            position: [0, 150],
            scale: 1,
            anchor: [0, 0],
            loop: false,
            callBack:()=>{
                setTimeout(() => {
                    parent.removeChild(movieclip);
                    r(1)
                }, 100);
            }
        });
        parent.addChild(movieclip);
        // setTimeout(() => {
        //     parent.removeChild(movieclip);
        //     r(1)
        // }, 1000);
        // movieclip.once('boomOver', () => {
        //     parent.removeChild(movieclip);
        //     r(1)
        // }, this,true)
    })
}

export const playBoom = (parent) => {
    return playMovieClip(parent, 'fail', ['fail1.png', 'fail2.png', 'fail3.png', 'fail4.png', 'fail5.png', 'fail6.png', 'fail7.png', 'fail8.png'], 5);
}
export const playSuccess = (parent) => {
    return playMovieClip(parent, 'success', ['success1.png', 'success2.png', 'success3.png', 'success4.png', 'success5.png', 'success6.png', 'success7.png', 'success8.png', 'success9.png'], 5);
}