import { _decorator } from "cc";
import { Snake } from "./Snake";
import { MainGame } from "./MainGame";
import { AIController } from "./AI/AIController";
import { aiPool } from "./Manager/CommonPool";

const { ccclass } = _decorator;

@ccclass("AISnake")
export class AISnake extends Snake {

    private aiController: AIController;
    private updateTimer: number = 0;
    private readonly UPDATE_INTERVAL: number = 0.1;

    async init(config: any) {
        await super.init(config);
        // const difficulty = 1 + Math.random() * 4;
        this.aiController = new AIController(this, 5);
    }

    onEnable() {
        super.onEnable();

        // const eye = this.head.getChildByName("范围").getComponent(Collider2D);
        // eye.on(Contact2DType.BEGIN_CONTACT, this.onBeginEye, this);

    }

    // onBeginEye(selfCollider: Collider2D, otherCollider: Collider2D) {
    //     super.onBeginEye(selfCollider, otherCollider);
    //     if (otherCollider.group === PhysicsGroup["Body"] && otherCollider.tag != this.tag) {
    //         // 碰到其他蛇身
    //         // this.setAngle(this.head.angle + 180);
    //         // this.isFast = true;
    //         this.setState(AIState.ESCAPING, otherCollider.node.parent.getComponent(Snake));
    //     }
    // }

    death() {
        super.death();

        this.node.removeFromParent();

        aiPool.put(this.node);

        MainGame.ins.initAnimal(1);

    }

    onUpdate(dt: number) {
        if (!this.isLife) return;

        this.updateTimer += dt;
        if (this.updateTimer >= this.UPDATE_INTERVAL) {
            this.updateTimer = 0;
            this.aiController.update(dt);
        }

        super.onUpdate(dt);
    }

}