import {
    _decorator,
    SpriteFrame,
    math,
    Sprite,
    Component,
    Prefab,
    instantiate,
} from "cc";
import { Global } from "db://assets/Scripts/Scenes/MainGame/Global";
import { executePreFrame, getItemGenerator } from "db://assets/Scripts/Utils/ExecutePreFrame";
import { Food } from "../Props/Food";
import { foodPool } from "./CommonPool";
import { PropBase } from "../Props/PropBase";

const { ccclass, property } = _decorator;

/**
 * 食物管理器
 */
@ccclass("FoodManger")
export class FoodManger extends Component {

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

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

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


    @property({ type: [SpriteFrame] })
    foods: SpriteFrame[] = [];

    @property(Prefab)
    private foodPrefab: Prefab = null;

    max: number = 10;


    onLoad() {
    }

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

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


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

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

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

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

        const item = foodPool.get() || instantiate(this.foodPrefab);

        // 随机选择食物类型
        const index = math.randomRangeInt(0, this.foods.length);

        // 设置食物属性
        item.angle = math.randomRange(0, 360);
        item.setPosition(x, y);
        item.getComponent(Sprite).spriteFrame = this.foods[index];
        item.getComponent(Food).init(energy);
        this.node.addChild(item);
    }



    async initFoods(infoArr: { x: number, y: number, energy: number }[]) {

        const initItem = (index: number) => {
            const bp = infoArr[index];
            this.add(bp.x, bp.y, bp.energy);
        };

        await executePreFrame(getItemGenerator(infoArr.length, initItem), 1, this);
    }

}
