import m from 'mithril';
import { Gauge } from 'components/widgets/gauge';
import { Pipe } from 'utilities/pipe';

require('./gauge-linear.css');

export class GaugeLinear extends Gauge {
	protected svgPaddingTop = 0.0;
	private bottomWidth: number;
	private topWidth: number;
	
	constructor(vnode: any) {
		super(vnode);
		
		this.bottomWidth = vnode.attrs.bottomWidth || 1.0;
		this.topWidth = vnode.attrs.topWidth || 1.0;
	}
	
	createSvg(svgElement: SVGElement) {
		let w = Math.round(svgElement.clientWidth);
		let h = Math.round(svgElement.clientHeight);
		let paddingTop = Math.round(svgElement.clientHeight * this.svgPaddingTop);
		
		svgElement.setAttribute('viewBox', "0 0 "+w+" "+h);
		
		let svgRound = (v: number) => Math.round(v * 100.0) / 100.0;

		let bg = document.createElementNS('http://www.w3.org/2000/svg', 'path');
		//bg.setAttribute('width', w.toString());
		//bg.setAttribute('height', (h - paddingTop).toString());
		//bg.setAttribute('y', paddingTop.toString());
		bg.setAttribute('d', 'M0,'+paddingTop+' L'+svgRound(w*this.topWidth)+','+paddingTop+' L'+svgRound(w*this.bottomWidth)+','+h+' L0,'+h+' Z');
		bg.classList.add('gauge-bg');
		svgElement.append(bg);
		
		let barHeight = 10;
		const barGap = barHeight * 0.2;
		let numBars = Math.round((h - paddingTop) / (barHeight + barGap));
		
		let bh = ((h - paddingTop) - (numBars+1)*barGap) / numBars;
		barHeight = Math.round(bh);
		
		for(let barIdx = 0; barIdx < numBars; ++barIdx) {
			let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
			let barW = w * ((barGap + barIdx * (bh+barGap))/(h - paddingTop) * (this.topWidth - this.bottomWidth) + this.bottomWidth);
			let barW1 = w * ((barGap + barIdx * (bh+barGap) + bh)/(h - paddingTop) * (this.topWidth - this.bottomWidth) + this.bottomWidth);
			barW = Math.min(barW, barW1);
			bar.setAttribute('width', (barW - barGap * 2).toString());
			bar.setAttribute('height', barHeight.toString());
			bar.classList.add('gauge-bar');
			bar.classList.toggle('lit', false);
			
			bar.setAttribute('x', barGap.toString());
			bar.setAttribute('y', (h - barIdx * (bh+barGap) - barGap - barHeight).toString());
			
			svgElement.append(bar);
			
			this.bars.push(bar);
		}
	}
	
	oncreate(vnode: any) {
		let svgElement: SVGElement = vnode.dom.querySelector('svg');
		this.createSvg(svgElement);
		
		super.oncreate(vnode);
	}
}
