const {ccclass, property} = cc._decorator;

@ccclass
export default class StarScore extends cc.Component {

    starLength = 0;
    addStar() {
        this.starLength++;
        let length = this.starLength;

        const starLayout = cc.find('layout', this.node);
        starLayout.removeAllChildren();
        const paddingY = starLayout.getComponent(cc.Layout).spacingY;

        for (let i = 0; i < length; i++) {
            const starBase = cc.instantiate(cc.find('StarBase', this.node));
            starBase.name = `starBase_${i}`;
            starBase.active = true;
            starBase.scale = this.Between(0.5, (starLayout.height / length - paddingY) / starBase.height, 1);
            starBase.parent = starLayout;
        }
        this.currentStarIdx = 0;
    }

    clearAllStar() {
        const starLayout = cc.find('layout', this.node);
        starLayout.removeAllChildren();
        this.starLength = 0;
        this.currentStarIdx = 0;
    }

    currentStarIdx = 0;
    showStar() {
        const starBase = cc.find(`layout/starBase_${this.currentStarIdx}`, this.node);
        if (!starBase) {
            return;
        }
        const star = starBase.getChildByName('Star');
        const starBig = star.getChildByName('StarBig');
        starBig.scale = 1;
        star.active = true;
        star.scaleX = 0.7 / starBase.scale;
        star.scaleY = 1 / starBase.scale;
        star.angle = 90;
        const canvas = cc.find('Canvas');
        const startPos = this.exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 2));
        const middlePos = this.exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 4));
        star.x = startPos.x;
        star.y = startPos.y - starBig.height;

        console.log('middlePos = ' + JSON.stringify(middlePos));
        cc.tween(star)
            .to(0.3, { y: middlePos.y + 80 }, { easing: 'quadOut' })
            .to(0.1, { y: middlePos.y + 40, scaleX: 1.2 / starBase.scale, scaleY: 0.8 / starBase.scale }, { easing: 'quadOut' })
            .to(0.1, { y: middlePos.y, scaleX: 1 / starBase.scale, scaleY: 1 / starBase.scale }, { easing: 'quadOut' })
            .delay(0.1)
            .to(0.8, { angle: -720, scale: 1 })
            .start();

        cc.tween(star)
            .delay(0.6)
            .to(0.8, { x: 0 }, { easing: 'quadIn' })
            .start();
        cc.tween(star)
            .delay(0.6)
            .to(0.8, { y: 0 }, { easing: 'quadOut' })
            .start();

        cc.tween(starBig)
            .delay(0.6)
            .to(0.8, { scale: 0 }, { easing: 'quadOut' })
            .call(() => {
                // this.checkGameEnd();
            })
            .start();

        this.currentStarIdx++;
    }

    Between(a, b, c) {
        return [a, b, c].sort()[1];
    }

    exchangeNodePos(targetNode, baseNode, basePos) {
        return targetNode.convertToNodeSpaceAR(baseNode.convertToWorldSpaceAR(cc.v2(basePos.x, basePos.y)));
    }
}
