
const { ccclass, property } = cc._decorator;

@ccclass
export default class HuController extends cc.Component {

    private spine: sp.Skeleton = null;

    private _isRotate: boolean = false;
    private _pointStart: cc.Vec2;

    protected onLoad(): void {
        this.spine = this.node.getComponent(sp.Skeleton);
        this.setRotateAnim();

        // this.node.on(cc.Node.EventType.TOUCH_START, this.toggleAnim, this);
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this)
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this)

        // this.spine.setCompleteListener((trackEntry) => this.setRotateAnim());

    }

    private onTouchStart(event: cc.Event.EventTouch): void {
        this._pointStart = event.getLocation();
        this.spine.timeScale = 0;
    }

    private onTouchEnd(): void {
        // this.spine.setAnimation(1, "Rotate", false);
        this.spine.timeScale = 0;
    }

    private onTouchMove(event: cc.Event.EventTouch): void {
        const newPoint = event.getLocation();
        const distance = newPoint.x - this._pointStart.x;
        if (Math.abs(distance) < 5) {
            this.spine.timeScale = 0;
            return;
        }

        console.log('distance', distance)
        this._pointStart = newPoint;
        this.spine.timeScale = distance > 0 ? -0.5 : 0.5;
    }

    private setRotateAnim(): void {
        this.spine.setAnimation(1, "Rotate", false);
        this.spine.timeScale = 0.2;
    }

    private pauseAnim(): void {
        this.spine.timeScale = 0;
    }

    private unPauseAnim(): void {
        this.spine.timeScale = 0.2;
        // this.node.scaleX *= -1;
    }

    private toggleAnim(): void {
        if (this._isRotate) {
            this.unPauseAnim();
        } else {
            this.pauseAnim();
        }
        this._isRotate = !this._isRotate;
    }

    private setIdleAnim(): void {
        this.spine.setAnimation(1, "Idle", false);
    }
}
