import m from 'mithril';
import { Widget } from 'components/widgets/widget';
import { Pipe } from 'utilities/pipe';

require('./gauge.css');

export class Gauge extends Widget {
	private gaugeValue: Pipe<number>;
	private gaugeMaxValue: number;
	private unit: string;
	private decimals: number;
	
	protected bars: SVGGeometryElement[] = [];
	private integralValueElement: HTMLElement;
	private decimalValueElement: HTMLElement;
	
	constructor(vnode: any) {
		super(vnode);
		
		this.gaugeValue = vnode.attrs.gaugeValue || new Pipe(0.0);
		this.gaugeMaxValue = vnode.attrs.gaugeMaxValue || 1.0;
		this.unit = vnode.attrs.unit || '';
		this.decimals = vnode.attrs.decimals || 0;
		
		this.gaugeValue.onChange(() => this.updateGauge());
	}
	
	view(vnode: m.Vnode<{}, {}>): m.Children {
		return <div class="widget gauge" style={'flex: ' + this.widgetWidth}>
			<p><span class="integral-value"></span><span class="decimal-value"></span><span class="unit">{this.unit}</span></p>
			<svg>
			</svg>
		</div>;
	}
	
	updateGauge() {
		let value = Math.max(0.0, Math.min(this.gaugeMaxValue, this.gaugeValue.get()));
		
		let integralValue = Math.floor(value);
		let decimalValue = value - integralValue;
		
		this.integralValueElement.innerText = integralValue.toFixed(0);
		this.decimalValueElement.innerText = this.decimals > 0 ? decimalValue.toFixed(this.decimals).substr(1) : '';
		
		let ratio = value / this.gaugeMaxValue;
		let numBars = this.bars.length;
		let litBars = Math.round(ratio * numBars);
		for(let barIdx = 0; barIdx < numBars; ++barIdx) {
			let bar = this.bars[barIdx];
			bar.classList.toggle('lit', barIdx < litBars);
		}
	}
	
	oncreate(vnode: any) {
		this.integralValueElement = vnode.dom.querySelector('span.integral-value');
		this.decimalValueElement = vnode.dom.querySelector('span.decimal-value');
		
		this.updateGauge();
	}
}
