import axios from 'axios';
import { isArrayLike, isNil, map, merge } from 'lodash';
import { stringify } from 'qs';
import application from '~/application.mjs';
import { Action, Actions } from './classes/Actions.mjs';
export function create(data) {
    return new Action(data)
}
export function createBatch(actions) {
    if (isArrayLike(actions)) {
        actions = map(actions, function (data) {
            if (data instanceof Action)
                return data;

            return new Action(data)
        });
    } else {
        actions = [];
    }

    return new Actions(actions)
}
export function run(data) {
    return create(data).run()
}
export function runBatch(actions) {
    return createBatch(actions).run()
}
export function requestVirtualPage(page, query, data) {
    return new Promise(function (resolve, reject) {
        const request = {
            method: 'get',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-Bitrix-Csrf-Token': application.options.site.csrf,
                'Bx-Ajax': true
            },
            url: application.options.template.directory + 'request.php',
            params: merge({}, query, {
                route: page,
                siteId: application.options.site.id,
                templateId: application.options.template.id
            }),
            paramsSerializer: function (params) {
                return stringify(params, {
                    arrayFormat: 'brackets'
                });
            },
            responseType: 'text'
        };

        if (!isNil(data)) {
            request.method = 'post';
            request.data = stringify(data);
        }

        axios(request).then(response => {
            if (response.status === 200) {
                resolve(response.data);
            } else {
                reject({
                    code: 'badResponse',
                    message: 'Bad response',
                    data: response
                });
            }
        }, reason => {
            reject({
                code: 'networkError',
                message: 'Network error',
                data: reason
            })
        })
    })
}
