/**
 * Created by rockyl on 2019-05-14.
 *
 * 倒计时
 */

import ScillaComponent from "components/base/ScillaComponent";
import {resource, ScillaEvent, Sheet} from "scilla";
import TextureRenderer from "components/renderer/TextureRenderer";

function getTextureNameSample(second){
	return `${second}.png`;
}

export default class CountDown extends ScillaComponent {
	numberSheet: resource;
	seconds: number;
	onComplete: ScillaEvent = new ScillaEvent();
	interval = 1000;
	hideWhenStop = true;

	$getTextureName: (second: number)=>string;

	private _textureRenderer: TextureRenderer;
	private _timer;
	private _remainSeconds;

	constructor(){
		super();

		this.$getTextureName = getTextureNameSample;
	}

	onCreate() {
		super.onCreate();
		this._textureRenderer = this.getComponent(TextureRenderer);
	}

	play(){
		if(this.seconds > 0){
			this.entity.enabled = true;
			this._remainSeconds = this.seconds;
			this.stop();
			this.onTimer();
			this._timer = setInterval(this.onTimer, this.interval);
		}
	}

	stop(){
		if(this._timer){
			clearInterval(this._timer);
			this._timer = null;
			if(this.hideWhenStop){
				this.entity.enabled = false;
			}
		}
	}

	private onTimer=()=>{
		if(this._remainSeconds <= 0){
			this.onComplete.invoke();
			this.stop();
			return;
		}

		let sheet = this.numberSheet;

		this._textureRenderer.texture = sheet.getTexture(this.$getTextureName(this._remainSeconds));

		this._remainSeconds--;
	}
}

