import m from 'mithril';

export interface Status {
	batteryVoltage: number; // in Volts
	motorCurrent: number; // in Amperes
	speed: number; // in meters per second
	temperature: number; // in Celcius degrees
	altitude: number; // in meters above sea level
};

interface ApiStatus {
	v: number;
	c: number;
	s: number;
	t: number;
	alt: number;
}

export class MonitorApi {
	private mockServer: boolean;
	private lastStatus: Status = null;
	private static api: MonitorApi = null;
	
	constructor() {
		this.mockServer = window.location.protocol == "file:";
	}
	
	static get() {
		if(MonitorApi.api == null)
			MonitorApi.api = new MonitorApi();
		return MonitorApi.api;
	}
	
	getStatus() { return this.lastStatus; }
	
	async fetchStatus(): Promise<Status> {
		let apiStatus: ApiStatus;
		
		if(this.mockServer) {
			await new Promise(resolve => setTimeout(resolve, 200));
			apiStatus = {
				v: Math.random() * 20000 + 20000,
				c: Math.random() * 30000,
				s: Math.random() * 14000,
				t: Math.random() * 400 - 100,
				alt: Math.random() * 4500000 - 200000
			}
			setTimeout(() => m.redraw(), 0);
		} else {
			apiStatus = await m.request({
			    method: "GET",
			    url: "/api/status"
			});
		}
		
		this.lastStatus = {
			batteryVoltage: apiStatus.v / 1000,
			motorCurrent: apiStatus.c / 1000,
			speed: apiStatus.s / 1000,
			temperature: apiStatus.t / 10,
			altitude: apiStatus.alt / 1000
		};
		
		return this.lastStatus;
	}
}
