/**
 * Copyright (c) Mikhail Subbotin, 2020
 */

var syncRequest = function (url, data, method) {
    let xhr = new XMLHttpRequest();
    method = method || (data ? 'POST' : 'GET');
    xhr.open(method, url, false);
    xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
    let json = null;
    if (false) {
        json = data;
    }
    else if (data) {
        json = JSON.stringify(data);
    }
    try {
        xhr.send(json);
        if (xhr.status == 200) {
            return JSON.parse(xhr.response);
        }
        else if (xhr.status == 500) {
            throw new Error(JSON.parse(xhr.response).Message);
        }
        else {
            throw new Error(`${xhr.status}: ${xhr.statusText} \n ${xhr.response}`);
        }
    } catch (err) { 
        throw err;
    }
}

//            api("", 'POST', {}, null, prop.dataSource).then(
var aSyncRequest = function (url, data, method) {
    let externalMethod = {};
    externalMethod.url = url;
    return api("", method, data, null, externalMethod)
}


var api = (function () {
//    var _url = window.location.protocol + '//' + window.location.hostname + ':' +window.location.port + '/api/';
    var _url;
    if (false && globalSettings){
      _url = globalSettings.getBaseUrl();
    }
    var http = function http(method, type, data, dtype, externalMethod) {
        var config = {
            method: type || 'GET',
            headers: {
                  'am_DataFormat': '2',
//                  'Content-Type': 'application/json;charset=utf-8'
            },
//            mode: 'no-cors',
//            mode: 'cors',
            cache: 'no-cache',
//            credentials: 'same-origin',
        };

        var types = {json: 'json', xml: 'text'}

        dtype = dtype && types[dtype] || types.json;


        if (config.method.toUpperCase() == "POST" &&  data !== undefined) {
            config.body = JSON.stringify(data)
        }
        var urlMethod;
        var scriptMethod;
        var isUrl = true;
        if (externalMethod && (externalMethod.url || externalMethod.jsMethod)) {
            if (externalMethod.url) {
                urlMethod = externalMethod.url;
            }
            else if (externalMethod.jsMethod) {
                scriptMethod = window[externalMethod.jsMethod];
            }
        }
        else {
            var apiMethod;
            if (false && globalSettings){
              apiMethod = globalSettings.getUrlByMethod(method);
            }
            urlMethod = apiMethod.url;
            if (apiMethod.isScript) {  //|| apiMethod.script
                scriptMethod = window[apiMethod.script];
            }
        }
        var response;
        if (scriptMethod) {
            return new Promise((resolve, reject) => { resolve(scriptMethod(data)) });
        }
        else {
            response = fetch(urlMethod, config).catch(console.log);
            return response.then(r => r[dtype]() );
//            return response.then(r => r.text() );
        }
    };
    return http;
}());
