import m from 'mithril';
import { Page } from 'components/page';
import { MonitorApi, Status } from 'monitor-api';
import { Pipe } from 'utilities/pipe';

import { Clock } from 'components/widgets/clock';
import { GaugeLinear } from 'components/widgets/gauge-linear';
import { GaugeCircular } from 'components/widgets/gauge-circular';
import { GaugeBattery } from 'components/widgets/gauge-battery';

require('./dashboard-page.css');

export class DashboardPage extends Page {
	status: Status = null;
	autoRefresh = true;
	
	private power = new Pipe(0.0);
	private battery = new Pipe(0.0);
	private speed = new Pipe(0.0);
	
	oninit() {
		this.status = MonitorApi.get().getStatus();
		this.refresh();
	}
	
	onbeforeremove(vnode: m.Vnode<{}, {}>) {
    	this.autoRefresh = false;
	}
	
	async refresh() {
		let newStatus = await MonitorApi.get().fetchStatus();
		if(this.status == null)
			m.redraw();
		this.status = newStatus;
		
		this.power.set(this.status.batteryVoltage * this.status.motorCurrent);
		
		const minVoltage = 36.0;
		const maxVoltage = 42.0;
		let batteryRatio = Math.max(0.0, (this.status.batteryVoltage - minVoltage) / (maxVoltage - minVoltage)); 
		this.battery.set(batteryRatio * batteryRatio * 100.0); // TODO: find a better formula to estimate remaining energy from battery voltage and power
		
		this.speed.set(this.status.speed * 3.6); // convert m/s to km/h
		
		if(this.autoRefresh)
			setTimeout(() => { if(this.autoRefresh) this.refresh(); }, 150);
	}
	
	view() {
		return this.status
			? <div class="dashboard-page">
				<div class="widgets-row">
					<Clock/>
				</div>
				<div class="widgets-row" style="height: 40%">
					<GaugeLinear widgetWidth={0.2} gaugeValue={this.power} gaugeMaxValue={999.0} bottomWidth={0.4} unit="W" />
					<GaugeCircular widgetWidth={0.6} gaugeValue={this.speed} gaugeMaxValue={50.0} decimals={1} unit="km/h" />
					<GaugeBattery widgetWidth={0.2} gaugeValue={this.battery} gaugeMaxValue={100.0} unit="%" />
				</div>
			</div>
			: <p>Chargement...</p>;
	}
}
