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() * 6000 + 36000,
				c: Math.random() * 30000,
				s: Math.random() * 14000,
				t: Math.random() * 400 - 100,
				alt: Math.random() * 4500000 - 200000
			};*/
			let t = new Date().getTime() / 1000.0;
			apiStatus = {
				v: (Math.cos(t*0.4)+1.0)*0.5 * 6000 + 36000,
				c: (Math.cos(t*0.7)+1.0)*0.5 * 30000,
				s: (Math.cos(t*0.3)+1.0)*0.5 * 14000,
				t: Math.random() * 400 - 100,
				alt: Math.random() * 4500000 - 200000
			};
		} else {
			apiStatus = await new Promise<ApiStatus>((resolve, error) => {
				let request = new XMLHttpRequest();
				request.onreadystatechange = () => {
					if(request.readyState == 4) {
						if(request.status == 200) {
							resolve(JSON.parse(request.response));
						}
						else {
							error();
						}
					}
				};
				request.open('GET', '/api/status', true);
				request.send();
			});
		}
		
		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;
	}
}
