import {getApi, getHeaders} 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}) {
        let headers = Object.assign(getHeaders(), this.headers);
        for(let header in headers) {
            if(headers.hasOwnProperty(header)) {
                console.log(header, headers[header]);
                this.xhr.setRequestHeader(header, headers[header]);
            }
        }
        const formData = new FormData();

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

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

        this.xhr.send(formData);
    }
}

export {ApiFileSend};