import {
    _decorator,
    math,
    Component,
    Prefab,
    instantiate,
} from "cc";
import { Global } from "db://assets/Scripts/Scenes/MainGame/Global";
import { executePreFrame, getItemGenerator } from "db://assets/Scripts/Utils/ExecutePreFrame";

const { ccclass, property } = _decorator;

/**
 * 管理器
 */
export class ItemMgrBase extends Component {

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

    max: number = 10;

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

    /**
     * 初始化
     */
    async init(max: number) {
        this.max = max;
        await executePreFrame(getItemGenerator(max, this.initItem), 1, this);
    }


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

    /**
     * 检查
     */
    check() {
        const { total, max } = this;
        for (let i = total; i < max; i++) {
            this.add();
        }
    }

    /**
     * 添加
     */
    add(x?: number, y?: number) {

        // 如果没有指定位置,随机生成位置
        if (!x) {
            const { x: _x, y: _y } = Global.getRandomPosition(100);
            x = _x;
            y = _y;
        }

        const index = math.randomRangeInt(0, this.prefabs.length);
        const item = instantiate(this.prefabs[index]);

        item.setPosition(x, y);
        this.node.addChild(item);
    }

}
