import { AlTriggerStream, AlBehaviorPromise, AlLocation, AlExecutionContext, AlDatacenterSessionErrorEvent, AlDatacenterSessionEstablishedEvent, AlExternalTrackableEvent, AlStopwatch, AlBeforeNetworkRequest, AlAfterNetworkRequest } from '@al/core';
import axios from '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 AlConduitClient {
    constructor(context = AlExecutionContext.default) {
        this.context = context;
        /**
         * Receives a message from conduit, and dispatches it to the correct handler.
         */
        this.onReceiveMessage = (event) => {
            if (!event.data
                || typeof (event.data.type) !== 'string'
                || typeof (event.data.requestId) !== 'string'
                || !event.origin
                || !event.source) {
                //  Disqualify events that aren't of the correct type/structure
                return;
            }
            const originNode = this.context.resolveNodeByURI(event.origin);
            const originWhitelist = [AlLocation.MagmaUI, AlLocation.AccountsUI, AlLocation.LegacyUI];
            if (!originNode || !originWhitelist.includes(originNode.locTypeId)) {
                //  Ignore any events that don't originate from a whitelisted domain (currently, console.account.* or any defender stack)
                return;
            }
            switch (event.data.type) {
                case 'conduit.ready':
                    return this.onConduitReady(event);
                case 'conduit.getSession':
                case 'conduit.setSession':
                case 'conduit.deleteSession':
                case 'conduit.getGlobalSetting':
                case 'conduit.setGlobalSetting':
                case 'conduit.deleteGlobalSetting':
                case 'conduit.getGlobalResource':
                    return this.onDispatchReply(event);
                case "conduit.externalSessionReady":
                    return this.onExternalSessionEstablished(event);
                case "conduit.externalSessionError":
                    return this.onExternalSessionError(event);
                case "conduit.externalEvent":
                    return this.onExternalTrackableEvent(event);
                default:
                    console.warn('AlConduitClient: Ignoring unrecognized message type: %s', event.data.type, event);
                    break;
            }
        };
        /**
         * This validation step is included *mostly* for the sanity of developers.  It is remarkably easy to forget to start o3-portero :)  It
         * may help detect problems in production as a fringe benefit.
         */
        this.validateReadiness = () => {
            if (!AlConduitClient.conduitWindow && !AlConduitClient.conduitOrigin) {
                console.warn('Conduit Warning: no conduit.ready message was received from the console.account conduit application.  This may result in degradation or unavailability of authentication features in this application.');
            }
        };
    }
    start(targetDocument) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!targetDocument) {
                if (typeof (document) === 'undefined') {
                    console.log("AlConduitClient: cannot start in headless mode.");
                    return;
                }
                targetDocument = document;
            }
            if (AlConduitClient.refCount < 1) {
                AlConduitClient.refCount++;
                if (!AlConduitClient.conduitUri) {
                    AlConduitClient.conduitUri = yield this.calculateConduitURI();
                }
                AlConduitClient.document = targetDocument;
                if (targetDocument && targetDocument.body && typeof (targetDocument.body.appendChild) === 'function') {
                    AlConduitClient.document.body.appendChild(this.render());
                }
                AlStopwatch.once(this.validateReadiness, 5000);
            }
        });
    }
    render() {
        const fragment = AlConduitClient.document.createDocumentFragment();
        const container = AlConduitClient.document.createElement("div");
        container.setAttribute("id", "conduitClient");
        container.setAttribute("class", "conduit-container");
        window.addEventListener("message", this.onReceiveMessage, false);
        fragment.appendChild(container);
        container.innerHTML = `<iframe frameborder="0" src="${AlConduitClient.conduitUri}" style="width:1px;height:1px;position:absolute;left:-1px;top:-1px;"></iframe>`;
        return fragment;
    }
    calculateConduitURI() {
        return __awaiter(this, void 0, void 0, function* () {
            const residency = "US";
            let environment = this.context.environment;
            if (environment === 'development') {
                environment = 'integration';
            }
            let conduitUri = this.context.resolveURL(AlLocation.AccountsUI, '/conduit.html', null, { residency, environment });
            return conduitUri;
        });
    }
    ready() {
        return __awaiter(this, void 0, void 0, function* () {
            yield AlConduitClient.ready;
        });
    }
    stop() {
        if (AlConduitClient.refCount > 0) {
            AlConduitClient.refCount--;
        }
        if (AlConduitClient.refCount === 0 && AlConduitClient.document) {
            let container = AlConduitClient.document.getElementById("conduitClient");
            if (container) {
                AlConduitClient.document.body.removeChild(container);
            }
        }
    }
    destroy() {
        if (AlConduitClient.document) {
            let container = AlConduitClient.document.getElementById("conduitClient");
            if (container) {
                AlConduitClient.document.body.removeChild(container);
            }
        }
        AlConduitClient.document = undefined;
        AlConduitClient.conduitUri = undefined;
        AlConduitClient.conduitWindow = undefined;
        AlConduitClient.conduitOrigin = undefined;
        AlConduitClient.refCount = 0;
        AlConduitClient.requestIndex = 0;
        AlConduitClient.requests = {};
        AlConduitClient.externalSessions = {};
    }
    /**
     * Checks to see if a session with an external resource has been established.
     *
     * @param insightLocationId The external location ID.  If unspecified, the associated contextual location will be used by default.
     * @returns Boolean true or false.
     */
    checkExternalSession(insightLocationId) {
        let targetLocationId = insightLocationId || this.context.locationId;
        if (AlConduitClient.externalSessions.hasOwnProperty(targetLocationId)) {
            return AlConduitClient.externalSessions[targetLocationId].resolved;
        }
        return false;
    }
    /**
     * Waits for a session with an external resource to be established.
     *
     * @param insightLocationId The external location ID.  If unspecified, the contextual location will be used by default.
     * @returns A promise that resolves once the external resource's session has been established.
     *
     * Please note that attempting to await an unknown or gibberishy location will return a promise that never resolves.
     */
    awaitExternalSession(insightLocationId) {
        let targetLocationId = insightLocationId || this.context.locationId;
        if (this.checkExternalSession(targetLocationId)) {
            return Promise.resolve();
        }
        if (!AlConduitClient.externalSessions[targetLocationId]) {
            let listener = {
                promise: null,
                resolver: null,
                resolved: false
            };
            listener.promise = new Promise((resolve) => {
                listener.resolver = resolve;
            });
            AlConduitClient.externalSessions[targetLocationId] = listener;
        }
        return AlConduitClient.externalSessions[targetLocationId].promise;
    }
    /**
     * Retrieves session information from the conduit.  Resolves with valid session information if a session exists, or null if no session is established;
     * an error indicates a problem with conduit operation rather than the absence of a session.
     */
    getSession() {
        return this.request('conduit.getSession')
            .then(rawResponse => rawResponse.session);
    }
    /**
     * Sets session information TO the conduit.  Should always resolve with a copy of the session (including acting
     * account and active datacenter) that conduit considers most fresh.  Note that in rare cases this may
     * deviate from the session provided to this method, in which case the caller should update its data to reflect
     * conduit's.
     */
    setSession(sessionData) {
        return __awaiter(this, void 0, void 0, function* () {
            let result = yield this.request('conduit.setSession', { session: sessionData });
            return result.session;
        });
    }
    /**
     * Deletes existing session information.
     */
    deleteSession() {
        return this.request('conduit.deleteSession')
            .then(() => true);
    }
    /**
     * Retrieves a global setting from conduit's local storage
     */
    getGlobalSetting(settingKey) {
        return this.request("conduit.getGlobalSetting", { setting_key: settingKey })
            .then(rawResponse => rawResponse.setting);
    }
    /**
     * Sets a global setting to conduit's local storage
     */
    setGlobalSetting(key, data) {
        return this.request("conduit.setGlobalSetting", { setting_key: key, setting_data: data })
            .then(rawResponse => rawResponse.setting);
    }
    /**
     * Deletes a global setting from conduit's local storage
     */
    deleteGlobalSetting(settingKey) {
        return this.request('conduit.deleteGlobalSetting', { setting_key: settingKey })
            .then(rawResponse => rawResponse.result);
    }
    /**
     * Retrieves a global resource.
     */
    getGlobalResource(resourceName, ttl) {
        return this.request('conduit.getGlobalResource', { resourceName, ttl }, 10)
            .then(response => {
            if (!response.resource) {
                return Promise.reject(response.error || `AlConduitClient failed to retrieve global resource '${resourceName}'`);
            }
            return response.resource;
        });
    }
    onConduitReady(event) {
        AlConduitClient.conduitWindow = event.source;
        AlConduitClient.conduitOrigin = event.origin;
        AlConduitClient.ready.resolve(true);
        if (typeof (event.data.cookiesDisabled) === 'boolean' && event.data.cookiesDisabled) {
            console.warn("WARNING: conduit has indicated that 3rd party cookies are disabled, triggering session error event.");
            AlConduitClient.events.trigger(new AlDatacenterSessionErrorEvent("inapplicable", "cookie-configuration", event.data));
        }
    }
    onDispatchReply(event) {
        const requestId = event.data.requestId;
        if (!AlConduitClient.requests.hasOwnProperty(requestId)) {
            console.warn(`Warning: received a conduit response to an unknown request with ID '${requestId}'; multiple clients running?`);
            return;
        }
        else if (AlConduitClient.requests[requestId].canceled) {
            console.warn(`Warning: received a conduit response after its timeout expired; discarding.`);
            return;
        }
        AlConduitClient.requests[requestId].resolve(event.data);
        delete AlConduitClient.requests[requestId];
    }
    /**
     * Responds to external session ready messages.  If no one is awaiting readiness, it will simply create a resolved promise for that location.
     */
    onExternalSessionEstablished(event) {
        if (typeof (event.data.locationId) !== 'string') {
            return;
        }
        const session = AlConduitClient.externalSessions.hasOwnProperty(event.data.locationId) ? AlConduitClient.externalSessions[event.data.locationId] : null;
        if (session) {
            session.resolved = true;
            session.promise = Promise.resolve();
            if (session.resolver) {
                session.resolver(true);
            }
        }
        else {
            AlConduitClient.externalSessions[event.data.locationId] = {
                promise: Promise.resolve(),
                resolver: null,
                resolved: true
            };
        }
        AlConduitClient.events.trigger(new AlDatacenterSessionEstablishedEvent(event.data.locationId));
    }
    /**
     * Raises an AlDatacenterSessionEventEvent
     */
    onExternalSessionError(event) {
        AlConduitClient.events.trigger(new AlDatacenterSessionErrorEvent(event.data.locationId, event.data.errorType || "unknown", event.data));
    }
    /**
     * Pass the event upstream on the internal event bus
     */
    onExternalTrackableEvent(event) {
        AlConduitClient.events.trigger(new AlExternalTrackableEvent(event.data));
    }
    request(methodName, data = {}, timeout = 0) {
        const requestId = `conduit-request-${++AlConduitClient.requestIndex}-${Math.floor(Math.random() * 1000)}`;
        return new Promise((resolve, reject) => {
            AlConduitClient.requests[requestId] = { resolve, reject, canceled: false };
            AlConduitClient.ready.then(() => {
                /**
                 * Requests can be queued at any time in the application's lifespan, even before the conduit iframe has been created or communications
                 * have been established.  However, no actually message will be broadcast until the initial handshake has occurred.
                 */
                const payload = Object.assign({ type: methodName, requestId: requestId }, data);
                AlConduitClient.conduitWindow.postMessage(payload, AlConduitClient.conduitOrigin);
            });
            if (timeout > 0) {
                AlStopwatch.once(() => {
                    if (AlConduitClient.requests.hasOwnProperty(requestId)) {
                        //  The promise has not been resolved within the given timeout window
                        console.warn(`Conduit Warning: request '${methodName}' (ID ${requestId}) failed to resolve within ${timeout} seconds; aborting.`);
                        AlConduitClient.requests[requestId].reject(new Error(`Failed to receive response to '${methodName}' request within ${timeout}s`));
                        AlConduitClient.requests[requestId].canceled = true;
                    }
                }, Math.floor(timeout * 1000));
            }
        });
    }
}
AlConduitClient.events = new AlTriggerStream();
AlConduitClient.refCount = 0;
AlConduitClient.ready = new AlBehaviorPromise();
AlConduitClient.requests = {};
AlConduitClient.externalSessions = {};
AlConduitClient.requestIndex = 0;

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 AlBrowserExecutionContext extends AlExecutionContext {
    constructor() {
        super();
    }
    base64Decode(input) {
        return atob(input);
    }
    base64Encode(input) {
        return btoa(input);
    }
    handleRequest(requestConfig) {
        return __awaiter(this, void 0, void 0, function* () {
            this.dispatch(new 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 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.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);
            }
        }
    }
}

export { AlBrowserExecutionContext, AlConduitClient };
//# sourceMappingURL=al-core-platform-browser.esm2015.js.map
