import {
    _decorator,
    SpriteFrame,
    math,
    Sprite,
    Collider2D,
    Component,
    Prefab,
    instantiate, Vec2
} from "cc";
import { FoodType } from "db://assets/Scripts/Scenes/MainGame/Common/Enums";
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";

const { ccclass, property } = _decorator;

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

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

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

    maxFood: number = 100;

    onLoad() {
    }

    /**
     * 获取当前食物数量
     */
    getFoodSum() {
        return this.node.children.length || 0;
    }

    /**
     * 初始化食物
     */
    async init(maxFood: number = 100) {
        this.maxFood = maxFood;
        await executePreFrame(getItemGenerator(maxFood, this.initItem), 1, this);
        this.schedule(this.checkFood, 1);
    }

    /**
     * 检查食物
     */
    checkFood() {
        for (let i = this.getFoodSum(); i < this.maxFood; i++) {
            this.addFood();
        }
    }

    /**
     * 设置食物
     */
    addFood(x?: number, y?: number, energy: number = 1) {

        // 如果没有指定位置,随机生成位置
        if (!x) {
            x = math.randomRangeInt(-(Global.MAP_WIDTH / 2 - 50), Global.MAP_WIDTH / 2 - 50);
        }

        if (!y) {
            y = math.randomRangeInt(-(Global.MAP_HEIGHT / 2 - 50), Global.MAP_HEIGHT / 2 - 50);
        }

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

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

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

        // 设置碰撞类型
        const collider = food.getComponent(Collider2D);
        if (collider) {
            collider.tag = FoodType.FOOD;
        }

        food.active = true;
    }

    /**
     * 初始化单个食物
     */
    initItem = (_: number) => {
        // 随机生成位置
        const x = math.randomRangeInt(-(Global.MAP_WIDTH / 2 - 50), Global.MAP_WIDTH / 2 - 50);
        const y = math.randomRangeInt(-(Global.MAP_HEIGHT / 2 - 50), Global.MAP_HEIGHT / 2 - 50);

        this.addFood(x, y);
    };

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

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

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


}
