import { _decorator, Enum, SpriteFrame, math, v3, Sprite, Collider2D, Component, Prefab, ccenum } from "cc";
import { PoolManager } from "./PoolManager";
import { FoodType } from "./Enums";
import { Global } from "./Global";
import { MainGame } from "./MainGame";

const { ccclass, property } = _decorator;

/**
 * 食物项配置
 */
@ccclass("Item")
class Item {
  @property({ type: FoodType })
  type: FoodType = FoodType.FOOD;

  @property(SpriteFrame)
  sp: SpriteFrame = null;
}

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

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

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

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

  /**
   * 初始化食物
   */
  init(count: number = 100) {
    this.initFond(count);
  }

  /**
   * 设置食物
   */
  setFood(x?: number, y?: number) {

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

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

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

    // 从对象池获取食物节点
    const node = PoolManager.instance.getNode(
      this.foodPrefab,
      this.node,
      v3(x, y, 0)
    );

    // 设置食物属性
    node.angle = 0;
    node.setScale(1, 1);
    node.getComponent(Sprite).spriteFrame = this.foods[index].sp;

    // 设置碰撞类型
    const collider = node.getComponent(Collider2D);
    if (collider) {
      collider.tag = this.foods[index].type;
    }

    node.active = true;
  }

  /**
   * 初始化单个食物
   */
  private _initItem(index: number) {
    // 从对象池获取食物节点
    const node = PoolManager.instance.getNode(this.foodPrefab, this.node);

    // 随机生成位置
    const x = math.randomRangeInt(-(Global.MAP_WIDTH / 2 - 50), Global.MAP_WIDTH / 2 - 50);
    const y = math.randomRangeInt(-(Global.MAP_HIGHT / 2 - 50), Global.MAP_HIGHT / 2 - 50);

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

    // 设置食物属性
    node.angle = 0;
    node.setScale(1, 1);
    node.setPosition(x, y, 0);
    node.getComponent(Sprite).spriteFrame = this.foods[index].sp;

    // 设置碰撞类型
    const collider = node.getComponent(Collider2D);
    if (collider) {
      collider.tag = this.foods[index].type;
    }

    node.active = true;
  }

  /**
   * 初始化食物
   */
  initFond(count: number) {
    for (let i = 0; i < count; i++) {
      this._initItem(i);
    }
  }

}
