/**
 * Created by rockyl on 2019-05-23.
 *
 * Html渲染器
 */

import {engine, decorators, color} from "scilla";
import ScillaComponent from "../base/ScillaComponent";

const {dirtyFieldDetector} = decorators;

const floatLayerName = 'floatLayer';

function getFloatLayer(){
	let floatLayer:HTMLElement = <HTMLElement>engine.canvasElement.nextElementSibling;

	if(!floatLayer || floatLayer.id !== floatLayerName){
		floatLayer = document.createElement('div');
		floatLayer.id = floatLayerName;
		floatLayer.style.position = 'absolute';
		floatLayer.style.overflowY = 'auto';
		engine.canvasElement.parentElement.append(floatLayer)
	}

	return floatLayer;
}

function showFloatLayer(){
	let floatLayer = getFloatLayer();
	floatLayer.style.display = 'inherit';
}

function hideFloatLayer(){
	let floatLayer = getFloatLayer();
	floatLayer.style.display = 'none';
}

export default class HtmlRenderer extends ScillaComponent {
	@dirtyFieldDetector
	htmlText: string;
	@dirtyFieldDetector
	fontSize = 14;
	@dirtyFieldDetector
	color: color = '#000';

	onAwake() {
		super.onAwake();

		showFloatLayer();
	}

	onSleep() {
		super.onSleep();

		hideFloatLayer();
	}

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

		let floatLayer = getFloatLayer();
		let style = floatLayer.style;

		if(this['dirty']){
			this['dirty'] = false;

			floatLayer.innerHTML = this.htmlText;
			style.fontSize = this.fontSize + 'px';
			style.color = this.color;
		}

		if(this.htmlText){
			const {globalPosition: {x, y}, width, height} = this.transform;

			const {x: px, y: py} = engine.canvasPosToPagePos(x, y);
			const {x: pWidth, y: pHeight} = engine.canvasPosToPagePos(width, height);


			if(style.left !== (px - pWidth / 2) + 'px'){
				style.left = (px - pWidth / 2) + 'px';
			}
			if(style.top !== (py - pHeight / 2) + 'px'){
				style.top = (py - pHeight / 2) + 'px';
			}
			if(style.width !== pWidth + 'px'){
				style.width = pWidth + 'px';
			}
			if(style.height !== pHeight + 'px'){
				style.height = pHeight + 'px';
			}
		}
	}
}
