import { instantiate, Node, tween, v3, Vec3, _decorator } from 'cc';
import { BaseLayer } from '../../common/BaseLayer';
import { cocosUtil } from '../../utils/cocosUtil';
import { constants } from '../data/constants';
import { audioManager } from '../manager/audioManager';
import { playerModel } from '../model/playerModel';
const { ccclass, property } = _decorator;

@ccclass('CoinGetEffectLayer')
export class CoinGetEffectLayer extends BaseLayer {

    coinLayer: Node;
    coinNode: Node;

    posStart: Vec3;

    onLoad() {
        super.onLoad();

        this.coinLayer = this.getNodeByPath("coinLayer");
        this.coinNode = this.getNodeByPath("coinLayer/coin");

        this.posStart = this.obj.posStart;

        this.initUI();
    }

    initUI() {

        let pos = cocosUtil.convertToNodeSpace(this.coinNode, this.posStart);
        let posEnd = cocosUtil.convertToNodeSpace(this.coinNode, playerModel.instance.coinPosEnd);

        let num = 10 + Math.floor(Math.random() * 10);
        let count = 0;
        for (let i = 0; i < num; i++) {
            let coinNode = this.coinNode;
            if (i >= 1) {
                coinNode = instantiate(this.coinNode);
                coinNode.parent = this.coinLayer;
            }

            let posX = pos.x + Math.random() * 200 - 100;
            let posY = pos.y + Math.random() * 200 - 100;
            coinNode.setPosition(posX, posY);
            coinNode.setScale(0, 0, 1);

            let time = 0.5 + Math.random() * 0.5;
            tween(coinNode).to(0.2, {
                scale: v3(2, 2, 1)
            }).to(0.3, {
                scale: v3(1, 1, 1)
            }).to(time, {
                position: posEnd
            }, {
                easing: "cubicOut"
            }).call(() => {
                count++;
                coinNode.destroy();
                if (count >= num) {
                    this.closeLayer();
                }
            }).start();
        }

        audioManager.instance.playEffect(constants.audioNames.gold);
    }

}

