import { Component, _decorator, Node, EventTouch, systemEvent, input, Input, geometry, Camera, PhysicsSystem, director, v3, Vec3 } from "cc";
import { Checkpoint } from "../Checkpoint";
import { PuppetViewComp } from "../../puppet/view/PuppetViewComp";
import { oops } from "../../../../../extensions/oops-plugin-framework/assets/core/Oops";
import { GameEvent } from "../../common/config/GameEvent";
import { Puppet } from "../../puppet/puppet";

const { ccclass, property } = _decorator;

/** 关卡点击控制 */
@ccclass('CheckpointViewController')
export class CheckpointViewController extends Component {
    /** 角色对象 */
    checkpoint: Checkpoint = null!;

    @property({ type: Camera, tooltip: '主相机' })
    public mainCamera: Camera | null = null;

    // @property({ type: Node, tooltip: '待触摸物体' })
    // public node_touch_1: Node | null = null;

    private _ray: geometry.Ray = new geometry.Ray();

    onLoad() {
        const cameras = director.getScene().getComponentsInChildren(Camera);
        this.mainCamera = cameras.find(camera => camera.node.name === 'MainCamera');
        input.on(Input.EventType.TOUCH_END, this.onTouchStart, this);
    }

    onDestory() {
        input.off(Input.EventType.TOUCH_END, this.onTouchStart, this);
    }

    onTouchStart(event: EventTouch) {
        // 基于摄像机 画射线
        this.mainCamera?.screenPointToRay(event.getLocation().x, event.getLocation().y, this._ray);
        if (PhysicsSystem.instance.raycast(this._ray)) {
            const r = PhysicsSystem.instance.raycastResults;
            if (r.length > 0) {
                let element = r.reduce((min, current) => {
                    return !Number.isNaN(current.distance) && current.distance < min.distance ? current : min;
                }, r[0]);

                // console.log(this.node?.uuid)
                const view = element.collider.node?.getComponent(PuppetViewComp) as PuppetViewComp
                if (view) {
                    view.controller.onPuppetClick()
                    const puppet = view.ent as Puppet
                    if (puppet?.PuppetModel) {
                        oops.message.dispatchEvent(GameEvent.PuppetClick, [puppet.PuppetModel.x, puppet.PuppetModel.y])
                    }
                }
            }

            // for (let index = 0; index < r.length; index++) {
            //     const element = r[index];
            //     if(Number.isNaN(element.distance)){
            //         continue
            //     }


            //     break
            // }
        }
    }

}