/**
 * Created by rockyl on 2018-11-27.
 *
 * 触摸缩放交互效果组件
 */

import {createTween, createVector2D, ease, Ease, Tween, Vector2D,} from "scilla";
import {InteractComponent} from "../base";

export default class TouchZoom extends InteractComponent {
	scaleOffset: Vector2D = createVector2D(0.1, 0.1);
	duration: number = 200;
	easeName: Ease = Ease.backOut;

	private _zoomIn: Tween;
	private _zoomOut: Tween;
	private _touchBegin: boolean;

	onAwake() {
		super.onAwake();

		if (!this._zoomIn) {
			const {scaleOffset, duration, transform} = this;

			const easeFunc = ease[this.easeName];

			const scaleFrom = transform.scale.clone();
			const scaleTo = transform.scale.clone().add(scaleOffset);

			this._zoomIn = createTween(transform, false, {autoPlay: false, clazz: Vector2D, fields: ['x', 'y']})
				.to({scale: scaleTo}, duration, easeFunc);

			this._zoomOut = createTween(transform, false, {autoPlay: false, clazz: Vector2D, fields: ['x', 'y']})
				.to({scale: scaleFrom}, duration, easeFunc);
		}
	}

	onTouchBegin(e) {
		super.onTouchOver(e);

		if (this.interactable) {
			this._touchBegin = true;
			this._zoomIn.play(true);
		}
	}

	onGlobalTouchEnd(e) {
		super.onGlobalTouchEnd(e);

		if (this._touchBegin) {
			this._touchBegin = false;
			this._zoomOut.play(true);
		}

		return false;
	}
}
