import Api from './Api';
import {auth} from '../lib/Auth';

// GET
const GET = 'GET';

// POST
const POST = 'POST';
const PUT = 'PUT';

// DELETE
const DELETE = 'DELETE';

// UPLOAD
// todo: implement uploading form multipart etc., look at multer
const UPLOAD = 'UPLOAD';

const API_URL = {};
const DEFAULT_HEADER = {};

class ApiRequest {

    /**
     * @param api_name
     * @param type
     * @param endpoint
     * @param data
     */
    constructor(api_name, type, endpoint, data = {}) {
        if(API_URL[api_name]) {
            /**
             * @type {Api}
             */
            this.api = new Api(API_URL[api_name], type);
            this.info = this.api.provideData(endpoint, data);
            this.headers = {};
        } else {
            throw new Error('Api: Could not find configured Api: ' + api_name);
        }
    }

    header(headers = {}) {
        this.headers = headers;

        return this;
    }

    exec() {
        if('undefined' === typeof this.info.headers || [] === this.info.headers) {
            this.info.headers = {};
        }

        if(auth.is) {
            // when logged in
            // todo: add setting of header to Auth.js
            DEFAULT_HEADER['AUTHORIZATION'] = 'Bearer ' + auth.token;
        } else {
            delete DEFAULT_HEADER['AUTHORIZATION'];
        }
        this.info.headers = Object.assign(DEFAULT_HEADER, this.info.headers, this.headers);

        return this.api.fetch(this.info)
            .catch(error => {
                if('undefined' !== typeof Api.error_handler[error.code]) {
                    Api.error_handler[error.code]();
                }

                // if NOT (error happend and the received error has already payload) add generic error data
                if(!(error && error.data)) {
                    error = {
                        data: {
                            _internal: [{
                                msg: 'mo-response',
                                code: 0,
                                level: 'critical',
                            }]
                        },
                        error: error
                    }
                }

                throw error;
            });
    }

    debug(on = false) {
        this.api.debug = on;
        return this;
    }
}

const addApi = (name, url) => {
    API_URL[name] = url;
};

const getApi = (name) => {
    return API_URL[name];
};

const addHeader = (name, url) => {
    DEFAULT_HEADER[name] = url;
};

export {ApiRequest};

export {
    addApi,
    getApi,
    addHeader,
    GET,
    PUT,
    POST,
    DELETE,
    UPLOAD
};