import {auth} from '../lib/Auth';
import {getApi} from './ApiRequest';

// GET

class ApiFileSend {

    /**
     * @param endpoint
     * @param debug
     */
    constructor(endpoint, debug = false) {
        this.debug = debug;
        this.headers = {};

        this.url = getApi('file') + '/' + endpoint;

        this.xhr = new XMLHttpRequest();
        if(this.debug) {
            console.log('>> ' + this.url);
        }
        this.xhr.open('POST', this.url, true);
    }

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

        return this;
    }

    onProgress(evt) {
        this.xhr.upload.addEventListener('progress', (e) => {
            evt(e, this.xhr);
        });

        return this;
    }

    onFinish(evt) {
        this.xhr.addEventListener('readystatechange', (e) => {
            evt(e, this.xhr);
        });

        return this;
    }

    exec({data, file}) {
        if(auth.is) {
            // when logged in
            this.xhr.setRequestHeader('AUTHORIZATION', 'Bearer ' + auth.token);
        }
        const formData = new FormData();

        if(file) {
            formData.append('file', file);
        }

        if(data) {
            formData.append('data', JSON.stringify(data));
        }

        this.xhr.send(formData);
    }
}

export {ApiFileSend};