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

export class Petal {

    renderArr = [];

    images;

    ctx;

    playing = true;

    tempRenderArr = [];

    constructor(renderArr, images, ctx) {

        this.renderArr = renderArr;

        this.images = images;

        this.ctx = ctx;

        this.tempRenderArr = [];
    }

    stop(callback = null) {

        this.playing = false;

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

        checkFinish();
    }

    /**
   * 显示结束花瓣
   * @param rect {x,y,width, height} 花瓣显示位置及大小
   * @param mapScale
   * @param timeout 花瓣显示间隔
   * @param kinds 花瓣种类，即花瓣图片样式数组个数
   */
    showPetal(rect, mapScale: number, timeout: number, kinds = 9) {

        if (!this.playing) {
            return;
        }

        const petal = this.getPetal(rect, mapScale, kinds);
        this.renderArr.push(petal);
        this.tempRenderArr.push(petal);

        let toY = rect.y + rect.height;

        moveItem(petal, petal.x, toY + petal.height * petal.scaleY, petal['time'], () => {
            removeItemFromArr(this.renderArr, petal);
            removeItemFromArr(this.tempRenderArr, petal);
        });

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

        setTimeout(() => {
            this.showPetal(rect, mapScale, timeout);
        }, timeout);
    }

    /**
     * 得到花瓣
     * @param rect 
     * @param mapScale 
     * @param kinds 
     */
    private getPetal(rect, mapScale, kinds) {

        const petal = new MySprite(this.ctx);

        const id = Math.ceil(Math.random() * kinds);

        petal.init(this.images.get('petal_' + id));

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

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

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

        petal.y = rect.y - petal.height / 2 * petal.scaleY;

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

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

        return petal;
    }
}