/**
 * Created by rockyl on 2018/11/15.
 *
 */

import {Entity, getStageSize, ScillaComponent, createVector2D, Vector2D, math} from "scilla";
import Transform from "../base/Transform";

/**
 * 相机控制组件
 */
export default class CameraController extends ScillaComponent {
	target: Entity;
	viewportAnchor: Vector2D = createVector2D();
	targetPosition: Vector2D;
	maxScale = 1.2;

	private followPosition: Vector2D;

	private stageSize;

	onCreate() {
		super.onCreate();
	}

	onAwake() {
		super.onAwake();

		const {target, viewportAnchor} = this;

		this.stageSize = getStageSize();

		if (target) {
			this.targetPosition = target.getComponent(Transform).position;
		}
		this.followPosition = createVector2D();

		if (viewportAnchor) {
			const {width, height} = this.stageSize;
			const {x, y} = this.viewportAnchor;
			this.transform.position.setXY(width * x, height * y);
		}
	}

	onUpdate(t) {
		super.onUpdate(t);

		if (!this.targetPosition) {
			return;
		}

		const {transform: {scale, position}, stageSize: {width, height}, targetPosition: {x, y, length}, maxScale} = this;

		const newScale = maxScale - length * maxScale / 2048;
		scale.setXY(newScale, newScale);

		this.followPosition.setXY(width / 2, height / 2).subtract(this.targetPosition);

		position.copyFrom(math.lerpObj(position, this.followPosition, 0.1, Vector2D, ['x', 'y']));
	}

	onSleep() {
		super.onSleep();
	}

	onDestroy() {
		super.onDestroy();
	}
}
