import React from 'react';

function checkIt(resp) {
    if  ( parseInt(resp.status / 100, 10) === 2 ||
          parseInt(resp.status / 100, 10) === 3
        ) {
        return resp;
    } else {
        throw resp;
    }
}

function catchIt(err) {
    if (err.message === "Unexpected token O in JSON at position 0") {
        return "OK";
    }
    if ( parseInt(err.status / 100, 10) === 4 ){
        throw err;
    }
    else if ( parseInt(err.status / 100, 10) === 5 ){
        throw err;
    } else {
        return err;
    }
}


class API {
    constructor(baseURL = '', token) {
        // if (process.env.NODE_ENV === 'production' && !baseURL.includes('http')) {
            baseURL = "/api/" + baseURL;
        // }
        this.baseURL = baseURL;
        this.token   = token;
    }
    setToken(t) {this.token = t}

    get(url) {
        let urb = this.baseURL + url;
        return window.fetch(urb, {
            method: 'GET',
            headers: {
                'Content-Type':'application/json',
                'Token' : this.token
            }
        }).then(checkIt).then((r) => r.json()).catch(catchIt);
    }

    post(url, body) {
        let urb = this.baseURL + url;
        return window.fetch(urb, {
            method: 'POST',
            headers: {
                'Content-Type':'application/json',
                'Token' : this.token
            },
            body: JSON.stringify(body)
        }).then(checkIt).then((r) => r.json()).catch(catchIt);
    }

    put(url, body) {
        let urb = this.baseURL + url;
        return window.fetch(urb, {
            method: 'PUT',
            headers: {
                'Content-Type':'application/json',
                'Token' : this.token
            },
            body: JSON.stringify(body)
        }).then(checkIt).then((r) => r.json()).catch(catchIt);
    }

    delete(url) {
        let urb = this.baseURL + url;
        return window.fetch(urb, {
            method: 'DELETE',
            headers: {
                'Content-Type':'application/json',
                'Token' : this.token
            }
        }).then(checkIt).then((r) => r.json()).catch(catchIt);
    }
}

export default API;