import Signal from "../../../../core/events/signal/Signal.js";
import Vector2 from "../../../../core/geom/Vector2.js";
import { getTouchCenter } from "./getTouchCenter.js";
import { observePinch } from "./observePinch.js";

export class TouchDevice{

    /**
     * Current live position of the pointer
     * @readonly
     * @type {Vector2}
     */
    position = new Vector2();

    /**
     * @readonly
     * @type {Vector2}
     */
    #anchor_touch_last = new Vector2();

    #globalUp = new Signal();


    #touchStart = new Signal();
    #touchEnd = new Signal();
    #touchMove = new Signal();

    /**
     * @readonly
     */
    on = {
        pinch: new Signal(),
        pinchStart: new Signal(),
        pinchEnd: new Signal(),
    };

    constructor() {
        observePinch({
            touchStart: this.#touchStart,
            touchEnd: this.#touchEnd,
            touchMove: this.#touchMove,
            pinch: this.on.pinch,
            pinchStart: this.on.pinchStart,
            pinchEnd: this.on.pinchEnd,
            device: this
        });
    }

    /**
     *
     * @param {TouchEvent} event
     */
    #eventHandlerGlobalTouchEnd = (event) => {
        getTouchCenter(event.touches, this.position);
        this.#globalUp.send2(this.position, event);
    }

    /**
     *
     * @param {TouchEvent} event
     */
    #eventHandlerTouchEnd = (event) => {
        getTouchCenter(event.touches, this.position);
        this.#touchEnd.send2(this.position, event);
    }

    /**
     *
     * @param {TouchEvent} event
     */
    #eventHandlerTouchMove = (event) => {
        event.preventDefault();

        getTouchCenter(event.touches, this.position);

        const delta = new Vector2();

        delta.subVectors(this.position, this.#anchor_touch_last);

        this.#touchMove.send3(this.position, event, delta);

        this.#anchor_touch_last.copy(this.position);
    }

    /**
     *
     * @param {TouchEvent} event
     */
    #eventHandlerTouchStart = (event) => {
        getTouchCenter(event.touches, this.position);
        this.#touchStart.send2(this.position, event);

        this.#anchor_touch_last.copy(this.position);
    }
}