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

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

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

	private targetPosition: Vector2D;
	private followPosition: Vector2D;
	private _stageSize;

	onAwake() {
		super.onAwake();

		const {target,} = this;


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

		if(this.once){
			this.updateViewport();
		}
	}

	get stageSize(){
		if(!this._stageSize){
			this._stageSize = engine.renderContext.stageSize;
		}

		return this._stageSize;
	}

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

		if(!this.once){
			this.updateViewport();
		}
		this.followTarget();
	}

	onEditorUpdate(t){
		this.updateViewport();
	}

	updateViewport() {
		if (this.viewportAnchor) {
			const {width, height} = this.stageSize;
			const {x, y} = this.viewportAnchor;
			const {x: sx, y: sy} = this.transform.scale;

			this.transform.position.setXY(width * x * sx, height * y * sy);
		}
	}

	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, ['x', 'y']));
	}
}
