import ComponentBase from "../libs/new_wx/components/ComponentBase";
import MainScene from "./MainScene";

const createItem = (i, delay, mainscene) => {
    return setTimeout(() => {
        const starAni = new StarAni();
        starAni.image.source = 'main_icon' + i + '_png';
        starAni.x = 30;
        starAni.y = 9;
        mainscene.starWrapper.addChild(starAni);
        StarAni.list.push(starAni);
        // console.log(i)
    }, delay);
}

export default class StarAni extends ComponentBase {
    public tweenGroup: egret.tween.TweenGroup;
    image: eui.Image;
    static ALL_TOTAL = 15;
    static TOTAL = 4;
    static next;
    constructor() {
        super();
        this.loadSkin();
        this.start();
    }

    dispose() {
        this.tweenGroup.removeEventListener('complete', this.onTweenGroupComplete, this);
        this.tweenGroup.removeEventListener('itemComplete', this.onTweenItemComplete, this);
    }

    static timers: any[] = [];
    static list: StarAni[] = [];
    static reset(mainscene: MainScene) {
        StarAni.timers.forEach(timer => {
            clearTimeout(timer);
        });
        StarAni.timers = [];
        StarAni.list.forEach(star => {
            star.dispose();
            star.parent && star.parent.removeChild(star);
        });
        StarAni.list = [];
        StarAni.next = StarAni.TOTAL + 1;

        const interval = 6300 / StarAni.TOTAL;
        for (let i = 0; i < StarAni.TOTAL; i++) {
            StarAni.timers.push(createItem(i + 1, interval * i, mainscene));
        }
    }

    /**
     * 动画组中的一项播放完成
     */
    private onTweenItemComplete(event: egret.Event): void {
        const item = event.data as egret.tween.TweenItem;
        // console.log(item.target);
        // console.log('TweenItem play completed.');
        // console.log(StarAni.next);

        (item.target as eui.Image).source = `main_icon${StarAni.next}_png`;
        StarAni.next++;
        if (StarAni.next > StarAni.ALL_TOTAL)
            StarAni.next = 1;
    }

    /**
     * 动画组播放完成
     */
    private onTweenGroupComplete(): void {
        // console.log('TweenGroup play completed.');
        this.tweenGroup.play(0);
    }

    start() {
        super.start();
        this.tweenGroup.addEventListener('complete', this.onTweenGroupComplete, this);
        this.tweenGroup.addEventListener('itemComplete', this.onTweenItemComplete, this);
        this.tweenGroup.play(0);
    }
    get skinKey(): string { return 'StarAni' }

    initEvents() {

    }
    removeEvents() {

    }

}