import {
    MySprite,
    moveItem,
    removeItemFromArr,
    rotateItem,
    hideItem
} from './Unit';

export class Star {
    renderArr = [];

    images;

    ctx;

    playing = true;

    tempRenderArr = [];

    constructor(renderArr, images, ctx) {

        this.renderArr = renderArr;

        this.images = images;

        this.ctx = ctx;

        this.tempRenderArr = [];
    }

    /**
     * 显示小星星
     * @param rect 
     * @param mapScale 
     * @param showTime 每个星星显示时间
     * @param timeout 显示频率
     * @param number 显示个数
     */
    showStar(rect, mapScale: number, showTime = 2, timeout = 500, number = 10) {

        if (!this.playing) {
            return;
        }

        const star = this.getStar(rect, mapScale);
        this.renderArr.push(star);
        this.tempRenderArr.push(star);

        hideItem(star, showTime, () => {
            removeItemFromArr(this.renderArr, star);
            removeItemFromArr(this.tempRenderArr, star);
        });

        rotateItem(star, star['tr'], star['time']);

        setTimeout(() => {

            if (this.tempRenderArr.length < number) {
                this.showStar(rect, mapScale);
            }

        }, timeout);
    }

    stop(callback = null) {
        this.playing = false;

        const checkFinish = () => {
            if (this.tempRenderArr.length == 0) {
                if (callback) {
                    callback();
                }
            }
            else {
                setTimeout(() => {
                    checkFinish();
                }, 100);
                
            }
        }

        checkFinish();
    }

    /**
     * 得到星星
     * @param rect 
     * @param mapScale 
     */
    private getStar(rect, mapScale) {

        //console.log('show star:', rect);

        const star = new MySprite(this.ctx);

        star.init(this.images.get('icon_star'));

        const randomS = (Math.random() * 0.4 + 0.6) * mapScale;
        star.setScaleXY(randomS);

        const randomR = Math.random() * 360;
        star.rotation = randomR;

        const randomX = rect.x + Math.random() * rect.width;
        star.x = randomX;

        star.y = rect.y + Math.random() * rect.width;

        const randomT = 0.5 + Math.random() * 2;
        star['time'] = randomT;

        let randomTR = 360 * Math.random(); // - 180;
        if (Math.random() < 0.5) { randomTR *= -1; }
        star['tr'] = randomTR;

        return star;
    }
}