import application from '~/application.mjs';
import axios from 'axios';
import { isNil, merge } from 'lodash';
import { stringify } from 'qs';
export function request() {
    let method;
    let url;
    let data;
    let parameters;

    if (arguments.length === 0)
        return Promise.reject(new Error('Invalid request parameters'));

    if (arguments.length === 1) {
        data = arguments[0];
    } else if (arguments.length === 2) {
        method = arguments[0];
        data = arguments[1];
    } else {
        method = arguments[0];
        url = arguments[1];
        data = arguments[2];

        if (arguments.length > 3)
            parameters = arguments[3];
    }

    parameters = merge({}, parameters);

    if (isNil(method))
        method = 'get';

    if (isNil(url))
        url = window.location.href;

    return new Promise(function (resolve, reject) {
        parameters = merge({
            responseType: 'json'
        }, parameters, {
            data: null,
            method: method,
            url: url,
            headers: {
                'X-Bitrix-Csrf-Token': application.options.site.csrf,
                'Bx-Ajax': true
            }
        });

        if (!isNil(data)) {
            if (!isNil(window.FormData) && data instanceof window.FormData) {
                parameters.data = data;
            } else {
                parameters.data = stringify(data);
            }
        }

        axios(parameters).then(resolve, reject)
    })
}
