export default class API {

    defaultOp = {
        requestURI: "",
        maxRetry: 5,
        initialDelay: 1000, // 1 second
        maxBackoff: 1000 * 30, // 30 seconds
    };

    constructor(op){

        this.op = { ...this.defaultOp, ...op };
        this.requestURI = this.op.requestURI;
		this.online = true;
    }

    setRequestURI(uri){

        if( typeof uri === "string" && uri ){
            this.requestURI = uri;
        }
    }

    async send(action, payload){

		if(!this.requestURI){
			const error = {
				type: "bad request",
				msg: "Request URI not set"
			}
			console.log(error);
			return { success: false, error };
		}

        if(!this.online && action !== 'ping'){
			const error = {
				type: "offline",
				msg: "API is offline"
			}
			return { success: false, error }
        }

        const reqURI = `${this.requestURI}/action/${action}`;
        const reqBody = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        };

        let attempt = 0;
        let delay = this.op.initialDelay;
        while(attempt <= this.op.maxRetry){

			attempt++;

			try{
				const res = await fetch(reqURI, reqBody);
				if(res.ok){
					const data = await res.json();
					return data;
				} 
				else{
					const error = {
						type: "http",
						msg: `HTTP Error: ${res.status}`,
						status: res.status,
						attempt
					}
					console.log(error);
					window.dispatchEvent(new CustomEvent('api-failure', { detail: error }));
					return { success: false, error }
				}
			}
			catch(err){
				if(attempt > this.op.maxRetry){
					const error = {
						type: "network",
						msg: err.message,
						attempt
					}
					console.log(error);
					window.dispatchEvent(new CustomEvent('api-failure', { detail: error }));
					return { success: false, error }
				}
				// exponential backoff
				await new Promise(resolve => setTimeout(resolve, delay));
                delay = Math.min(delay * 2, this.op.maxBackoff);	
			}
		}
	}
	
   /**
	* Pure utility to check if the server is reachable.
	* Returns Boolean. No state side-effects.
	*/
	async isReachable(){

		try{
			const reqURI = `${this.requestURI}/action/ping`;
			const res = await fetch(reqURI, {
				method: 'HEAD',
				cache: 'no-store'
			});
			return res.ok;
		} 
		catch(e){
			return false;
		}
	}
}
