"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
class Proxy {
    constructor() {
        this.options = {};
    }
    prepare(url, method, params, body, query, headers) {
        //M.Rest.
        //console.log(url, method, params, body, query, headers);
        if (params && url) {
            params.forEach(function (param) {
                if (url) {
                    url = url.replace(':' + param.id, param.value);
                }
            });
        }
        if (query && query.length > 0) {
            url = url + '?' + query.join('&');
        }
        let formData = new FormData();
        Object.keys(body).forEach((key) => {
            formData.append(key, body[key]);
        });
        //add files
        //add headers
        this.url = url;
        this.request = new Request(url);
        this.options = {
            method: method,
            credentials: 'include',
            headers: Object.assign(headers, {
                'Content-Type': 'application/json'
            }),
            //headers: myHeaders,
            mode: 'cors',
            cache: 'default'
        };
        if (body && Object.keys(body).length > 0) {
            Object.assign(this.options, { body: JSON.stringify(body) });
        }
    }
    execute(responseCB, jsonCB, htmlCB) {
        return __awaiter(this, void 0, void 0, function* () {
            const response = yield fetch(this.request, this.options);
            if (responseCB) {
                responseCB(response);
            }
            try {
                let jsonResult = yield response.text();
                try {
                    jsonResult = JSON.parse(jsonResult);
                    if (jsonCB) {
                        jsonCB(jsonResult);
                    }
                }
                catch (error) {
                    if (htmlCB) {
                        htmlCB(jsonResult);
                    }
                }
                return jsonResult;
            }
            catch (error) {
                return response.text();
            }
            // return response.json();
            // throw new Error('Network response was not ok.');
        });
    }
}
exports.Proxy = Proxy;
