
import { screen, _decorator, Component, Node, EventTouch, Vec2, Vec3 } from 'cc';
import { BaseJoystick, IMoveDirection } from './BaseJoystick';
const { ccclass, property } = _decorator;

@ccclass('JoystickComponent')
export class JoystickComponent extends Component {
    @property({ type: Node, tooltip:"摇杆的那个点" })
    public UI_Joystick_Ctl!: Node;
    @property({ type: Node, tooltip:"所有事件的捕获区域" })
    public UI_Joystick_Capture!: Node;

    private baseCtl!: BaseJoystick;

    private MoveTouchId: number | null = null;
    private touchStartPos: Vec2 = new Vec2();
    private touchMovePos: Vec2 = new Vec2();

    private joystickDefPos: Vec3 = new Vec3();


    public onmove?: (dir: IMoveDirection) => void;
    public onmoveend?: () => void;

    start() {
        this.baseCtl = new BaseJoystick();
        this.baseCtl.onmove = (dir) => {
            this.onmove?.call(this, dir);
        };
        this.baseCtl.onmoveend = () => {
            this.endMove();
            this.onmoveend?.call(this);
        };

        this.UI_Joystick_Capture?.on(Node.EventType.TOUCH_START, this.onTouchStartCtlUnit, this);
        this.UI_Joystick_Capture?.on(Node.EventType.TOUCH_MOVE, this.onTouchMoveCtlUnit, this);
        this.UI_Joystick_Capture?.on(Node.EventType.TOUCH_END, this.onTouchEndCtlUnit, this);
        this.UI_Joystick_Capture?.on(Node.EventType.TOUCH_CANCEL, this.onTouchEndCtlUnit, this);
    }

    onTouchStartCtlUnit(ev: EventTouch) {
        //某个触点被用作移动了,其他触点不需要
        if (this.MoveTouchId !== null) return;

        this.MoveTouchId = ev.getID();
        ev.getUILocation(this.touchStartPos);

        Vec3.copy(this.joystickDefPos, this.node.position);
        //var maxH = this.UI_Joystick.parent?.getComponent(UITransform)?.height ?? 960;
        this.node.setPosition(this.touchStartPos.x, this.touchStartPos.y, this.joystickDefPos.z);

        //creator的UI坐标系, y轴是左下角向上, 所以要转一下
        this.baseCtl.touchStart(this.touchStartPos.x,  screen.windowSize.height  - this.touchStartPos.y);
    }
    onTouchMoveCtlUnit(ev: EventTouch) {
        if (this.MoveTouchId === null || ev.getID() != this.MoveTouchId) return;

        ev.getUILocation(this.touchMovePos);
        var reX = this.touchMovePos.x - this.touchStartPos.x;
        var reY = this.touchMovePos.y - this.touchStartPos.y;
        var ctlMove: Vec2 = new Vec2(reX, reY);
        ctlMove.normalize();
        ctlMove.multiplyScalar(30);
        this.UI_Joystick_Ctl.setPosition(ctlMove.x, ctlMove.y, 0);

        //creator的UI坐标系, y轴是左下角向上, 所以要转一下
        this.baseCtl.touchMove(this.touchMovePos.x, screen.windowSize.height  - this.touchMovePos.y);
    }
    onTouchEndCtlUnit(ev: EventTouch) {
        if (this.MoveTouchId === null || ev.getID() != this.MoveTouchId) return;
        this.baseCtl.touchEnd();
    }
    endMove() {
        this.MoveTouchId = null;
        this.UI_Joystick_Ctl.setPosition(new Vec3(0, 0, 0));
        this.node.setPosition(this.joystickDefPos);
    }
}
