import m from 'mithril';

export interface Status {
	batteryVoltage: number;
	motorCurrent: number;
	speed: number; // in meters per second
};

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

export class MonitorApi {
	constructor(private mockServer: boolean) {
	}
	
	async getStatus(): 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
			}
			setTimeout(() => m.redraw(), 0);
		} else {
			apiStatus = await m.request({
			    method: "GET",
			    url: "/api/status"
			});
		}
		
		return {
			batteryVoltage: apiStatus.v / 1000,
			motorCurrent: apiStatus.c / 1000,
			speed: apiStatus.s / 1000
		};
	}
}
