import m from 'mithril';
import { MonitorApi, Status } from './monitor-api';

require("./main-page.css");

export default class MainPage {
	api = new MonitorApi(false);
	status?: Status;
	autoRefresh = true;
	
	oninit() {
		this.refresh();
	}
	
	onbeforeremove() {
		this.autoRefresh = false;
	}
	
	async refresh() {
		this.status = await this.api.getStatus();
		if(this.autoRefresh)
			setTimeout(() => { if(this.autoRefresh) this.refresh(); }, 500);
	}
	
	view() {
		return this.status
			? <div class="main-page">
				<p>Tension batterie : {this.status.batteryVoltage.toFixed(3)}V</p>
				<p>Courant : {this.status.motorCurrent.toFixed(3)}A</p>
				<p>Puissance : {(this.status.batteryVoltage * this.status.motorCurrent).toFixed(1)}W</p>
				<p>Vitesse : {(this.status.speed * 3.6).toFixed(1)}km/h</p>
			</div>
			: <p>Chargement...</p>;
	}
}