import {
    _decorator,
    math,
    Collider2D,
    Component,
    Prefab,
    instantiate,
} from "cc";
import { EPropType } from "db://assets/Scripts/Scenes/MainGame/Common/Enums";
import { Global } from "db://assets/Scripts/Scenes/MainGame/Global";
import gameStore from "../../../store/gameStore";

const { ccclass, property } = _decorator;

/**
 * 福袋管理器
 */
@ccclass("LuckyBagManager")
export class LuckyBagManager extends Component {

    private static _ins: LuckyBagManager = null;
    static get ins() {
        return this._ins;
    }

    constructor() {
        super();
        LuckyBagManager._ins = this;
    }

    onDestroy() {
        if (LuckyBagManager._ins == this) {
            LuckyBagManager._ins = null;
        }
    }

    @property(Prefab)
    luckyBagPrefab: Prefab = null;

    @property({ type: [Prefab] })
    private prefabs: Prefab[] = [];

    /**
     * 获取数量
     */
    get total() {
        return this.node.children.length || 0;
    }

    /**
     * 初始化
     */
    init() {
        this.flush();
    }


    /**
     * 初始化单个
     */
    initItem = (_: number) => {
        this.add();
    };

    /**
     * 检查
     */
    check() {
        if (this.node.children.length <= 0) {
            this.flush();
        }
    }

    flush() {
        const { luckNum } = gameStore.gameInfo || {};
        const { currentAcquireNum } = gameStore.startInfo || {};

        const flushNum = Math.min(currentAcquireNum - luckNum, 3);

        this.add(flushNum);
    }

    /**
     * 添加
     */
    add(num: number = 1) {
        if (!num || num <= 0) return;

        const maxW = Global.MAP_WIDTH / 2 - 100;
        const maxH = Global.MAP_HEIGHT / 2 - 100;

        for (let i = 1; i <= num; i++) {
            const x = math.randomRange(-maxW, maxW);
            const y = math.randomRange(-maxH, maxH);
            const node = instantiate(this.luckyBagPrefab);

            // 设置食物属性
            node.setPosition(x, y);
            this.node.addChild(node);

            // 设置碰撞类型
            const collider = node.getComponent(Collider2D);
            if (collider) {
                collider.tag = EPropType.LUCK_BAG;
            }
        }
    }

}
