/**
 * Created by rockyl on 2019-01-02.
 *
 * Toast
 */

import {Entity, createTween, Tween, ease, engine,} from "scilla";
import ScillaComponent from "components/base/ScillaComponent";
import TextRenderer from "components/renderer/TextRenderer";
import Transform from "components/base/Transform";

export default class Toast extends ScillaComponent {
	Label: Entity;
	padding = 20;
	offsetY = 0;
	showDuration = 300;
	hideDuration = 300;

	private _bgTransform: Transform;
	private _labelRenderer: TextRenderer;
	private _labelTransform: Transform;
	private _tweenIn: Tween;
	private _tweenOut: Tween;
	private _timerDuration;

	onAwake() {
		super.onAwake();

		if (!this._bgTransform) {
			const {offsetY, hideDuration, showDuration, transform} = this;

			this._bgTransform = this.getComponent(Transform);
			this._labelRenderer = this.Label.getComponent(TextRenderer);
			this._labelTransform = this.Label.getComponent(Transform);

			this._tweenIn = createTween(this, transform, false, {autoPlay: false})
				.to({position: {x: 0, y: offsetY}}, showDuration, ease.cubicOut);
			this._tweenOut = createTween(this, transform, false, {autoPlay: false})
				.to({position: {y: 0}}, hideDuration, ease.cubicIn)
				.call(this.onHidden);

			this.transform.position.y = this.outPos;
		}
	}

	private get outPos(){
		return engine.renderContext.stageCenter.y + this._bgTransform.height;
	}

	show({content, duration = 1000}) {
		this.entity.enabled = true;

		const {_bgTransform, _labelRenderer, _labelTransform, padding} = this;

		_labelRenderer.text = content;
		_labelRenderer.measureBounds();

		_bgTransform.width = _labelTransform.width + padding * 2;
		_bgTransform.height = _labelTransform.height + padding * 2;

		this._tweenOut.queue[0].props.position.y = this.outPos;

		this._tweenIn.play(true);

		if (this._timerDuration) {
			clearTimeout(this._timerDuration);
			this._timerDuration = null;
		}
		this._timerDuration = setTimeout(() => {
			this.hide();
		}, duration);
	}

	hide() {
		this._tweenOut.play(true);
	}

	private onHidden() {
		this.entity.enabled = false;
	}
}
