'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var axios = require('axios');
var core = require('@al/core');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);

/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

class WrappedAxiosRequest {
    constructor(axios, request) {
        this.axios = axios;
        this.request = request;
        this.status = 0;
        this.statusText = "pending";
        this.headers = {};
        this.data = null;
    }
    execute() {
        return __awaiter(this, void 0, void 0, function* () {
            let axiosRequestConfig = this.convertRequest(this.request);
            yield this.axios(axiosRequestConfig);
            return this;
        });
    }
    complete(response) {
        this.rawResponse = response;
        this.status = response.status;
        this.statusText = response.statusText;
        this.headers = response.headers;
        this.data = response.data;
        if (this.status >= 200 && this.status < 300) {
            return Promise.resolve(response);
        }
        else {
            return Promise.reject(this);
        }
    }
    json() {
        return this.data;
    }
    convertRequest(request) {
        let requestConfig = {
            url: request.url || '',
            method: request.method || "GET",
            headers: request.headers || {},
            data: request.data || null,
            wrapper: this
        };
        if (typeof (request.responseType) !== 'undefined') {
            requestConfig.responseType = request.responseType;
        }
        if (typeof (request.credentialed) === 'boolean') {
            requestConfig.withCredentials = request.credentialed;
        }
        return requestConfig;
    }
}

class AlNodeExecutionContext extends core.AlExecutionContext {
    constructor() {
        super();
        this.setOption(core.ConfigOption.DisableEndpointsResolution, true);
        this.setOption(core.ConfigOption.ResolveAccountMetadata, false);
        this.setOption(core.ConfigOption.LocalManagedContent, true);
    }
    base64Encode(data) {
        return Buffer.from(data, 'utf8').toString('base64');
    }
    base64Decode(data) {
        return Buffer.from(data, 'base64').toString('utf8');
    }
    handleRequest(requestConfig) {
        return __awaiter(this, void 0, void 0, function* () {
            this.dispatch(new core.AlBeforeNetworkRequest(requestConfig)); //    Allow event subscribers to modify the request (e.g., add a session token header) if they want
            let wrapper = new WrappedAxiosRequest(this.getAxiosInstance(), requestConfig);
            let result = yield wrapper.execute();
            this.dispatch(new core.AlAfterNetworkRequest(requestConfig, result));
            return result;
        });
    }
    /**
     * Instantiate a properly configured axios client for services
     */
    getAxiosInstance() {
        if (this.axios) {
            return this.axios;
        }
        let headers = {
            'Accept': 'application/json, text/plain, */*'
        };
        this.axios = axios__default["default"].create({
            timeout: 0,
            withCredentials: false,
            headers: headers
        });
        this.axios.interceptors.request.use(this.axiosRequestHook);
        this.axios.interceptors.response.use(this.axiosResponseHook);
        return this.axios;
    }
    axiosRequestHook(config) {
        config.validateStatus = (responseStatus) => {
            //  This forces all responses to pass through our response interceptor, even error responses
            return true;
        };
        return config;
    }
    axiosResponseHook(response) {
        const wrappedConfig = response.config;
        if (wrappedConfig.wrapper) {
            return wrappedConfig.wrapper.complete(response);
        }
        else {
            if (response.status < 200 || response.status >= 400) {
                return Promise.reject(response);
            }
            else {
                return Promise.resolve(response);
            }
        }
    }
}

exports.AlNodeExecutionContext = AlNodeExecutionContext;
exports.WrappedAxiosRequest = WrappedAxiosRequest;
//# sourceMappingURL=al-core-platform-node.es5.js.map
