import { NumericValue } from 'components/widgets/numeric-value';

require('./chronometer.css');

export class Chronometer extends NumericValue {
	private realTimeValue = 0;
	private realTimeReference = 0;
	
	private animating = false;
	private shuttingDown = false;
	
	protected mainClassName() { return 'numeric-value chronometer'; }
	
	protected onValueChange(value: number) {
		let now = Date.now() / 1000;
		
		let realTimeValue = this.realTimeValue + (now - this.realTimeReference);
		
		if(Math.abs(value - realTimeValue) < 2.0)
			return;
			
		this.realTimeValue = value;
		this.realTimeReference = now;
		realTimeValue = value;
		this.startAnimation();
	}
	
	private startAnimation() {
		if(this.animating)
			return;
		this.animating = true;
		this.animate();
	}
	
	onbeforeremove(vnode: any) {
		this.shuttingDown = true;
		super.onbeforeremove(vnode);
	}
	
	private animate() {
		if(this.shuttingDown) return;
		
		let now = Date.now() / 1000;
		let realTimeValue = this.realTimeValue + (now - this.realTimeReference);
		
		let hours = Math.floor(realTimeValue / 3600);
		let minutes = Math.floor((realTimeValue - hours * 3600)/60);
		let seconds = Math.floor(realTimeValue - hours * 3600 - minutes * 60);
		
		this.integralValueElement.innerText = (hours < 10 ? '0' : '') + hours + ':' + (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
		
		setTimeout(() => this.animate(), (Math.ceil(realTimeValue) + 0.05 - realTimeValue) * 1000);
	}
}
