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

require('./numeric-value.css');

export class NumericValue extends Widget {
	protected value: Pipe<number>;
	protected minValue?: number;
	protected maxValue?: number;
	protected unit: string;
	protected decimals: number;
	
	protected icon?: string;
	
	protected integralValueElement: HTMLElement;
	protected decimalValueElement: HTMLElement;
	
	constructor(vnode: any) {
		super(vnode);
		
		this.value = vnode.attrs.value || new Pipe(0.0);
		this.minValue = vnode.attrs.minValue || null;
		this.maxValue = vnode.attrs.maxValue || null;
		this.unit = vnode.attrs.unit || '';
		this.decimals = vnode.attrs.decimals || 0;
		
		this.icon = vnode.attrs.icon || null;
		
		this.value.onChange(() => this.onValueChange(this.getClampedValue()));
	}
	
	view(vnode: m.Vnode<{}, {}>): m.Children {
		return <div class={'widget ' + this.mainClassName()} style={'flex: ' + this.widgetWidth}>
			<p>
				{this.icon ? <div class="value-icon"><img src={this.icon}></img></div> : null}
				<span class="integral-value"></span>
				<span class="decimal-value"></span>
				<span class="unit">{this.unit}</span>
			</p>
			{this.graphicalRepresentation(vnode)}
		</div>;
	}
	
	protected mainClassName() { return 'numeric-value'; }
	
	protected graphicalRepresentation(vnode: m.Vnode<{}, {}>): m.Children {
		return [];
	}
	
	private getClampedValue() {
		let value = this.value.get();
		if(this.minValue !== null) value = Math.max(value, this.minValue);
		if(this.maxValue !== null) value = Math.min(value, this.maxValue);
		return value;
	}
	
	protected onValueChange(newValue: number) {
		let valueStr = newValue.toFixed(this.decimals);
		let parts = valueStr.split('.');
		
		this.integralValueElement.innerText = parts[0];
		this.decimalValueElement.innerText = this.decimals > 0 ? '.' + parts[1] : '';
	}
	
	oncreate(vnode: any) {
		this.integralValueElement = vnode.dom.querySelector('span.integral-value');
		this.decimalValueElement = vnode.dom.querySelector('span.decimal-value');
		
		this.onValueChange(this.getClampedValue());
	}
}
