/**
 * Created by rockyl on 2019-05-15.
 *
 * 跑数字
 */

import ScillaComponent from "components/base/ScillaComponent";
import TextRenderer from "components/renderer/TextRenderer";
import {createTween, ScillaEvent} from "scilla";

function renderSimple(v) {
	return Math.floor(v).toString();
}

export default class RunNumber extends ScillaComponent {
	duration = 3000;
	onComplete = new ScillaEvent();

	private _textRenderer: TextRenderer;
	private _t;

	$renderFunc: (v: number) => string = renderSimple;

	onAwake() {
		super.onAwake();

		this._textRenderer = this.getComponent(TextRenderer);
	}

	play(to, from?) {
		if(!this._textRenderer){
			return Promise.resolve();
		}

		from = from === undefined ? parseFloat(this._textRenderer.text) : from;

		return new Promise(resolve => {
			createTween(this, this, true)
				.set({t: from})
				.to({t: to}, this.duration)
				.call(()=>{
					resolve();
					this.onComplete.invoke();
				});
		})
	}

	get t() {
		return this._t;
	}

	set t(v) {
		this._t = v;

		this._textRenderer.text = this.$renderFunc(v);
	}
}
