import { _decorator, Component, Prefab,Node, instantiate, RigidBody2D, input, Input, EventTouch, UITransform, v3, Collider2D, Contact2DType } from "cc";
import { Board } from "./Board";
import { FruitNode } from "./FruitNode";
const { ccclass, property } = _decorator;

@ccclass("GameManager")
export class GameManager extends Component {
    @property(Node) 
    fruitStart: Node = null;

    @property(Node) 
    fruitParent: Node = null;

    @property(Prefab) 
    fruitPrefabs: Prefab[] = [];

    private _curFruit: Node = null;

    start() {
        this.createFruit()

        input.on(Input.EventType.TOUCH_START, this.handelTouchStart, this)
        input.on(Input.EventType.TOUCH_MOVE, this.handelTouchMove, this)
        input.on(Input.EventType.TOUCH_END, this.handelTouchEnd, this)
    }

    handelTouchStart(event: EventTouch) {
        
    }

    handelTouchMove(event) {
        const curPos = event.getUILocation();
        const parentPos = this.fruitParent.getComponent(UITransform).convertToNodeSpaceAR(v3(curPos.x, curPos.y, 0));
        // 当前水果坐标
        const fruitPos = this._curFruit.getPosition();
        fruitPos.x = parentPos.x
        this._curFruit.setPosition(fruitPos); 
    }

    handelTouchEnd(event) {
        if (!this._curFruit) return;

        this._curFruit.getComponent(RigidBody2D).enabled = true;

        this._curFruit = null;

        this.scheduleOnce(this.createFruit, 2)
    }

    private createFruit() {
        const fruitId = Math.floor(Math.random() * 3);
        const fruitNode = instantiate(this.fruitPrefabs[fruitId]);
        fruitNode.setPosition(this.fruitStart.position);
        fruitNode.getComponent(RigidBody2D).enabled = false;

        fruitNode.getComponent(FruitNode).fruitId = fruitId
        // 监听水果碰撞事件
        const collider = fruitNode.getComponent(Collider2D);
        collider.on(Contact2DType.BEGIN_CONTACT, this.handelBeginContact, this)

        fruitNode.getComponent(RigidBody2D).gravityScale = 3; // 重力
        this.fruitParent.addChild(fruitNode);

        this._curFruit = fruitNode;
    }

    handelBeginContact(selfContact: Collider2D, otherContact: Collider2D) {
       if(otherContact.group !== Math.pow(2, 1)) return;

       console.log(111)

    }
}
