/**
 * Created by rockyl on 2018-12-05.
 *
 */

import {ScillaComponent} from "scilla";
import Renderer from "../renderer/Renderer";
import Transform from "../base/Transform";

/**
 * 相对布局组件
 */
export default class RelativeLayout extends ScillaComponent {
	left: number = NaN;
	right: number = NaN;
	top: number = NaN;
	bottom: number = NaN;
	horizontalCenter: number = NaN;
	verticalCenter: number = NaN;

	once: boolean = true;

	onCreate() {
		super.onCreate();
	}

	onAwake() {
		super.onAwake();

		this.adjust();
	}

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

		if (!this.once) {
			this.adjust();
		}
	}

	onSleep() {
		super.onSleep();
	}

	onDestroy() {
		super.onDestroy();
	}

	adjust = () => {
		const {
			entity, entity: {parent}, transform, transform: {position, pivot: {x: ax, y: ay},},
			left, right, top, bottom, horizontalCenter, verticalCenter
		} = this;

		const hasLeft = !isNaN(left);
		const hasRight = !isNaN(right);
		const hasTop = !isNaN(top);
		const hasBottom = !isNaN(bottom);
		const hasHorizontalCenter = !isNaN(horizontalCenter);
		const hasVerticalCenter = !isNaN(verticalCenter);

		const parentRenderers = parent.getComponents(Renderer);
		for (let parentRenderer of parentRenderers) {
			parentRenderer.measureBounds();
		}
		const parentTransform:Transform = parent.getComponent(Transform);
		let pWidth, pHeight;
		if(parentRenderers.length > 0){
			const parentBounds = parentRenderers[0].bounds;
			pWidth = parentBounds.width;
			pHeight = parentBounds.height;
		}else{
			pWidth = parentTransform.explicitWidth;
			pHeight = parentTransform.explicitHeight;
		}
		const {x: pax, y: pay} = parentTransform.pivot;

		const renderers = entity.getComponents(Renderer);
		for (let renderer of renderers) {
			renderer.measureBounds();
		}
		let {width, height, } = transform;

		let {x, y} = position;

		let widthModified = false, heightModified = false;

		//adjust
		{
			if (hasHorizontalCenter) {
				x = (pWidth - width) / 2 - pWidth * pax + width * ax;
			} else if (hasLeft) {
				if (hasRight) {
					widthModified = true;
					width = pWidth - right - left;
					x = (left - right) / 2 - (0.5 - ax) * width;
				} else {
					x = left - pWidth * pax + width * ax;
				}
			} else if (hasRight) {
				x = -right + pWidth * (1 - pax) - width * (1 - ax);
			}

			if (hasVerticalCenter) {
				y = (pHeight - height) / 2 - pHeight * pay + height * ay;
			} else if (hasTop) {
				if (hasBottom) {
					heightModified = true;
					height = pHeight - bottom - top;
					y = (top - bottom) / 2 - (0.5 - ay) * height;
				} else {
					y = top - pHeight * pay + height * ay;
				}
			} else if (hasBottom) {
				y = -bottom + pHeight * (1 - pay) - height * (1 - ay);
			}
		}

		position.x = x;
		position.y = y;

		if(widthModified){
			transform.width = width;
		}
		if(heightModified){
			transform.height = height;
		}

		if(widthModified || heightModified){
			for (let renderer of renderers) {
				renderer.measureBounds();
			}
		}
	}
}
