/**
 * 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 {
	viewportAnchor: Vector2D = createVector2D(0.5, 0.5);
	target: Entity;
	maxScale = 1.2;

	private targetPosition: Vector2D;
	private followPosition: Vector2D;
	private stageSize;

	onCreate() {
		super.onCreate();
	}

	onAwake() {
		super.onAwake();

		const {target,} = this;

		this.stageSize = getStageSize();

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

		this.updateViewport();
	}

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

		this.followTarget();
	}

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

	followTarget() {
		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']));
	}
}
