import { loggerNamed } from '@amp-metrics/mt-client-logger-core';
import { reflect, network as network$1 } from '@amp-metrics/mt-metricskit-utils-private';

/*
 *  src/environment.js
 *  mt-event-queue
 *
 *  Copyright © 2016-2019 Apple Inc. All rights reserved.
 *
 */

var environment = {
    /**
     ************************************ PUBLIC METHODS/IVARS ************************************
     */

    /**
     * Allows replacement of one or more of this class' functions
     * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
     * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
     * Your delegate can be a true object instance, an anonymous object, or a class object.
     * Your delegate is free to have as many additional non-matching methods as it likes.
     * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
     *
     * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
     * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
     * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
     * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
     * but override the "appVersion" method again, this time with their own supplied delegate.
     *
     * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
     * This allows the delegate to, essentially, call "super" before or after it does some work.
     * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
     * @example:
     * To override one or more methods, in place:
     *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
     * To override one or more methods with a separate object:
     *      eventRecorder.setDelegate(eventRecorderDelegate);
     *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
     *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
     *                                       sendMethod: 'itms'};
     * To override one or more methods with an instantiated object from a class definition:
     *      eventRecorder.setDelegate(new EventRecorderDelegate());
     *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
     *          function EventRecorderDelegate() {
     *         }
     *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
     *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
     *                                                          return 'itms';
     *                                                      };
     * To override one or more methods with a class object (with "static" methods):
     *      eventRecorder.setDelegate(EventRecorderDelegate);
     *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
     *          function EventRecorderDelegate() {
     *         }
     *         EventRecorderDelegate.recordEvent = itms.recordEvent;
     *         EventRecorderDelegate.sendMethod = function sendMethod() {
     *                                                return 'itms';
     *                                            };
     * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
     * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
     * otherwise returns false.
     */
    setDelegate: function setDelegate(delegate) {
        return reflect.attachDelegate(this, delegate);
    },

    /**
     * An object that conforms to the WindowOrWorkerGlobalScope API:
     * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope
     * @return {WindowOrWorkerGlobalScope}
     */
    globalScope: function globalScope() {
        return reflect.globalScope();
    }
};

/*
 *  src/utils/constants.js
 *  mt-event-queue
 *
 *  Copyright © 2019 Apple Inc. All rights reserved.
 *
 */

// These constants are exposed publicly

/**
 * Possible send method types to record events
 */
var SEND_METHOD = {
    AJAX: 'ajax',
    AJAX_SYNCHRONOUS: 'ajaxSynchronous',
    IMAGE: 'image',
    BEACON: 'beacon',
    BEACON_SYNCHRONOUS: 'beaconSynchronous'
};

/*
 *  src/event_recorder/base.js
 *  mt-event-queue
 *
 *  Copyright © 2016-2019 Apple Inc. All rights reserved.
 *
 */

var IDENTIFIABLE_FIELDS = ['dsId', 'consumerId'];

/**
 * Clone the passed-in source config with the provided topic
 *
 * Since we support multiple config instances instead of singleton config in mt-client-config.
 * We have to pass the topicConfig instance to all places that we were passing a topic string to in the past.
 * The problem there was if a caller wants to send an event to a sub-topic of the config and the config has some overriding values for the sub-topic,
 * we need both config and the sub-topic to collect the values for the sub-topic.
 * we either have to pass topicConfig and the sub-topic everywhere or create a new config with the sub-topic based on the topic config of the main topic.
 * So we clone a new config by the main topic config with the sub-topic in the root entry(evenRecorder.recordEvent()) then all related logic would use that cloned config to load the config for the sub topic
 *
 * NOTE: We create an object and put the main topic config to the prototype of it because in that way,
 * the cloned config still be able to share the same functions from the source config and when the source config getting cleanup, the cloned config also gets cleanup.
 * The main purpose of the clone is overriding the main topic with the passed-in topic
 *
 * For Example:
 * // We have a topic config with "topic_A" as the main topic, and a "topic_B" as the sub-topic inside of the config
 * var topicConfig = {
 *     metricsUrl: 'https://xp.apple.com/report',
 *     postFrequency: 60000
 *     topic_B: {
 *         postFrequency: 30000
 *     }
 * };
 * var metricsKit = new MetricsKit('topic_A'); // which will have the above topicConfig for "topic_A"
 * var eventFields = metricsKit.eventHandlers.enter.metricsData();
 * var eventRecorder = new EventRecorder(metricsKit);
 * eventRecorder.recordEvent('topic_B', eventFields);
 *
 * For above example, the recordEvent function will clone a new config by the topicConfig(topic_A) with the "topic_B".
 * So underneath of the event recorder, we could get the correct values for "topic_B"
 * topicConfig.value('postFrequency'); -> 30000
 * event_queue.metricsUrlForConfig() -> https://xp.apple.com/report/topic_B
 *
 * @param sourceConfig
 * @param topic
 */
function cloneTopicConfigWithTopic(sourceConfig, topic) {
    var clonedConfig = {
        _topic: topic
    };

    // inherit the class to have fields, methods and delegated methods from the source config
    Object.setPrototypeOf(clonedConfig, sourceConfig);

    return clonedConfig;
}

/**
 * Abstract Event Recorder class
 * @constructor
 */
var Base = function Base(configInstance) {
    this._validateConfig(configInstance);
    // @private
    this._config = configInstance;

    // @private
    this._topicConfigCache = {};

    // @private
    this._topicPropsCache = {};

    this.logger = loggerNamed('mt-event-queue');
};

/**
 * Previously, this private method validated the config from metricskit but now it will validate the
 * config directly
 *
 * @param {Object} config Configuration object
 */
Base.prototype._validateConfig = function validateConfig(config) {
    var errorPostfix = 'please call constructor with a valid Config instance first.';
    if (!config) {
        throw new TypeError('Unable to find config, ' + errorPostfix);
    } else if (!config.topic || !reflect.isFunction(config.topic)) {
        throw new TypeError('Unable to find config.topic function, ' + errorPostfix);
    } else if (
        !config.metricsDisabledOrDenylistedEvent ||
        !reflect.isFunction(config.metricsDisabledOrDenylistedEvent)
    ) {
        throw new TypeError('Unable to find config.metricsDisabledOrDenylistedEvent function, ' + errorPostfix);
    } else if (!config.removeDenylistedFields || !reflect.isFunction(config.removeDenylistedFields)) {
        throw new TypeError('Unable to find config.removeDenylistedFields function, ' + errorPostfix);
    }
};

/**
 * Remove identify fields from the eventFields based on the topic properties
 * @param {String} topic defines the Figaro "topic" that this event should be stored under
 * @param {Object} eventFields a JavaScript object which will be converted to a JSON string and sent to AMP Analytics immediately.
 * @private
 */
Base.prototype._removeIdentifiableFieldsForTopic = function _removeIdentifiableFieldsForTopic(topic, eventFields) {
    this._topicPropsCache[topic] = this._topicPropsCache[topic] || {};
    if (this._topicPropsCache[topic].anonymous) {
        IDENTIFIABLE_FIELDS.forEach(function (field) {
            delete eventFields[field];
        });
    }
};

/**
 * Record event
 * Subclasses implement this method to handle how to record an event
 * @abstract
 * @param {Object} eventFields a JavaScript object which will be converted to a JSON string and sent to AMP Analytics immediately.
 * @returns {Promise}
 */
Base.prototype._record = function _record(eventFields) {};

/**
 * clean resources of event recorder
 * Subclasses implement this method to handle how to clean resources
 * @returns {Promise} returns a Promise if the cleanup will asynchronously execute or undefined for synchronously executing
 */
Base.prototype.cleanup = function cleanup() {
    this._config = null;
    this._topicConfigCache = null;
    this._topicPropsCache = {};
};

/**
 * Records an event as JSON
 * TODO: We should look at simplifying the process of using multiple topics. By deprecating recordEvent(topic, eventFields) in favor of recordEvent(eventFields) using the topic from the Kit.
 * @param {String} topic an 'override' topic which will override the main topic.
 * NOTE:
 *       1. RecordEvent needs to check the denylisted event/fields. The passed-in topic may not be enough to check them. If MetricsKit's config had a subsection for the passed-in topic, then the denylisting would work properly.
 *       2. The eventFields were generated with the config of Metricskit. If sending them to another topic, the eventFields might have incorrect values.
 * @param {Object} eventFields a JavaScript object which will be converted to a JSON string and sent to AMP Analytics immediately.
 * @returns {Promise} a Promise that returns the recorded event, or "null" if no object was recorded (e.g. if "eventFields" is null, or "disabled" is true, eventFields.eventType is one of the denylistedEvents, etc.)
 */
Base.prototype.recordEvent = function recordEvent(topic, eventFields) {
    if (!this._config || !eventFields) {
        return Promise.resolve(null);
    }
    var config = this._config;
    var self = this;
    var args = arguments;

    // We do this if `topic` is a sub-topic of the configuration
    if (reflect.isDefinedNonNullNonEmpty(topic) && topic !== config.topic()) {
        config = this._topicConfigCache[topic];

        if (!config) {
            config = this._topicConfigCache[topic] = cloneTopicConfigWithTopic(this._config, topic);
        }
    }

    // NOTE: Typically all event_handlers will check for this as well because that way if a client overrides "recordEvent", these checks will still take effect.
    //       We also test it here in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
    return config
        .metricsDisabledOrDenylistedEvent(eventFields.eventType)
        .then(function (disabledOrBlacklistedEvent) {
            if (disabledOrBlacklistedEvent) {
                return null;
            }
            return config
                .removeDenylistedFields(eventFields)
                .then(function () {
                    self._removeIdentifiableFieldsForTopic(topic, eventFields);
                    return self._record.apply(self, [config].concat(Array.prototype.slice.call(args, 1)));
                })
                .then(function () {
                    return eventFields;
                });
        })
        .catch(function (error) {
            self.logger.error(error);
            return null;
        });
};

/**
 * The methodology being used to send batches of events to the server
 * This field should be hardcoded in the client based on what method it is using to encode and send its events to Figaro.
 * The three typical values are:
 *      "itms" - use this value when/if JavaScript code enqueues events for sending via the "itms.recordEvent()" method in ITML.
 *      "itunes" - use this value when/if JavaScript code enqueues events by calling the "iTunes.recordEvent()" method in Desktop Store apps.
 *      "javascript" - use this value when/if JavaScript code enqueues events for sending via the JavaScript eventQueue management. This is typically only used by older clients which don't have the built-in functionality of itms or iTunes available to them.
 * @example "itms", "itunes", "javascript"
 * @returns {String}
 */
Base.prototype.sendMethod = function sendMethod() {
    return 'javascript';
};

/**
 * Set related properties for the giving topic
 * @param {String} topic defines the Figaro "topic" that this event should be stored under
 * @param {Object} properties the properties for the topic
 * @param {Boolean} properties.anonymous true if sending all events for the topic with credentials omitted(no cookies, no PII fields)
 */
Base.prototype.setProperties = function setProperties(topic, properties) {
    this._topicPropsCache[topic] = this._topicPropsCache[topic] || {};
    this._topicPropsCache[topic] = properties;
};

/*
 *  src/network.js
 *  mt-event-queue
 *
 *  Copyright © 2017 Apple Inc. All rights reserved.
 *
 */

/**
 * Network request methods exposed so delegate callers can override
 * @constructor
 */
var network = {
    /**
     * Allows replacement of one or more of this class' functions
     * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
     * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
     * Your delegate can be a true object instance, an anonymous object, or a class object.
     * Your delegate is free to have as many additional non-matching methods as it likes.
     * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
     *
     * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
     * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
     * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
     * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
     * but override the "appVersion" method again, this time with their own supplied delegate.
     *
     * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
     * This allows the delegate to, essentially, call "super" before or after it does some work.
     * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
     * @example:
     * To override one or more methods, in place:
     *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
     * To override one or more methods with a separate object:
     *      eventRecorder.setDelegate(eventRecorderDelegate);
     *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
     *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
     *                                       sendMethod: 'itms'};
     * To override one or more methods with an instantiated object from a class definition:
     *      eventRecorder.setDelegate(new EventRecorderDelegate());
     *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
     *          function EventRecorderDelegate() {
     *         }
     *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
     *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
     *                                                          return 'itms';
     *                                                      };
     * To override one or more methods with a class object (with "static" methods):
     *      eventRecorder.setDelegate(EventRecorderDelegate);
     *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
     *          function EventRecorderDelegate() {
     *         }
     *         EventRecorderDelegate.recordEvent = itms.recordEvent;
     *         EventRecorderDelegate.sendMethod = function sendMethod() {
     *                                                return 'itms';
     *                                            };
     * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
     * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
     * otherwise returns false.
     */
    setDelegate: function setDelegate(delegate) {
        return reflect.attachDelegate(this, delegate);
    },
    /**
     * Covers private util network functions for delegation
     */
    makeAjaxRequest: network$1.makeAjaxRequest
};

/*
 *  src/event_queue.js
 *  mt-event-queue
 *
 *  A low-level, cross-platform, metrics batcher and emitter.
 *  Adapted from Jingle (its.MetricsQueue)
 *
 *  Copyright © 2016-2017 Apple Inc. All rights reserved.
 *
 */

/**
 * Some ugly user agent detection, because iOS browsers refuse to send image pings onpagehide
 * @return {Boolean} true if this browser is running on an iOS device
 */
function _isIOS() {
    var userAgent = navigator.userAgent;

    // IE for Windows Phone 8.1 contains the string 'iPhone', so we have to check for that too...
    // https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
    return /iPad|iPhone|iPod/.test(userAgent) && userAgent.indexOf('IEMobile') == -1;
}

/**
 * Check if the fetch API is supported by the Browser and check if "keepalive" is available by checking for Firefox
 * @returns {Boolean} true if fetch API is supported
 */
function _isFetchAndKeepaliveAvailable() {
    return reflect.isFunction(environment.globalScope().fetch) && !/Firefox/.test(navigator.userAgent);
}

function _logger() {
    return loggerNamed('mt-event-queue');
}

var CONSTANTS = {
    DEFAULT_REQUEST_TIMEOUT: 10000, // TODO: move to config
    EVENTS_KEY: 'events',
    EVENT_DELIVERY_VERSION: '1.0',
    MAX_PERSISTENT_QUEUE_SIZE: 100, // TODO: move to config
    RETRY_EXPONENT_BASE: 2, // TODO: move to config
    SEND_METHOD: SEND_METHOD,
    URL_DELIVERY_VERSION: 2,
    PROPERTIES_KEY: 'properties'
};

var _eventQueue = {
    /**
     * A dictionary of event queues by topic
     * Each topic queue is an object that holds an array of the events themselves and information about send attempts for that topic (postIntervalToken, retryAttempts)
     * We use an in-memory queue for two reasons:
     * 1) We expect all remaining events to get sent on app exit via flushUnreportedEvents (ignoring the failed send case)
     * 2) Stringifying and writing is expensive - as much as 5ms to write 100 events to localStorage on an older (2013) mobile device,
     *    and that would have to happen each time we did an event insertion, since localStorage only allows the saving of stringified (serialized) data.
     */
    eventQueues: {},

    /**
     * Determines whether events will be sent via a post interval.
     * If this value is false then the client must perform flushing manually and events will not be scheduled or sent automatically.
     */
    postIntervalEnabled: true,

    /**
     * Enqueue an event to a particular topic queue
     * @param {Object} topicConfig a config instance for the Figaro "topic" that this event should be stored under
     * @param {Object} eventFields a JavaScript object which will be converted to a JSON string and enqued for sending to Figaro according to the postFrequency schedule
     * @return {Promise} a Promise that returns the current event, if it was successfully queued, otherwise null
     */
    enqueueEvent: function enqueueEvent(topicConfig, eventFields) {
        if (topicConfig && eventFields && topicConfig.topic()) {
            var topic = topicConfig.topic();
            _eventQueue.eventQueues = _eventQueue.eventQueues || {};
            _eventQueue.eventQueues[topic] = _eventQueue.eventQueues[topic] || {};
            _eventQueue.eventQueues[topic].topicConfig = topicConfig;
            _eventQueue.eventQueues[topic].flushConfig = _eventQueue.eventQueues[topic].flushConfig || {};
            _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY] =
                _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY] || [];
            _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY].push(eventFields); // Add the new event to the end of our eventQueue

            // Set flushing related config values
            if (Object.keys(_eventQueue.eventQueues[topic].flushConfig).length === 0) {
                Promise.all([
                    topicConfig.value('metricsUrl'),
                    topicConfig.value('requestTimeout'),
                    topicConfig.value('postFrequency')
                ]).then(function (results) {
                    var flushConfig = _eventQueue.eventQueues[topic].flushConfig;
                    flushConfig.metricsUrl = results[0];
                    flushConfig.requestTimeout = results[1];
                    flushConfig.postFrequency = results[2];
                });
            }

            return topicConfig.value('maxPersistentQueueSize').then(function (maxQueueSize) {
                maxQueueSize = maxQueueSize || CONSTANTS.MAX_PERSISTENT_QUEUE_SIZE;
                _eventQueue.trimEventQueues(_eventQueue.eventQueues, maxQueueSize);
                return eventFields;
            });
        } else {
            return Promise.resolve(null);
        }
    },

    /**
     * Currently this just ensures that each queue is <= maxEventsPerQueue, but in the future we could remove oldest events in a queue-independent way
     * @param {Object} eventQueues a dictionary of event queues (arrays) by topic
     * @param {int} maxEventsPerQueue
     */
    trimEventQueues: function trimEventQueues(eventQueues, maxEventsPerQueue) {
        var topics = Object.keys(eventQueues);
        if (topics.length) {
            topics.forEach(function (topic) {
                var events = eventQueues[topic][CONSTANTS.EVENTS_KEY];
                if (events && events.length && events.length > maxEventsPerQueue) {
                    _logger().warn(
                        'eventQueue overflow, deleting LRU events: size is: ' +
                            events.length +
                            ' which is over max size: ' +
                            maxEventsPerQueue
                    );
                    eventQueues[topic][CONSTANTS.EVENTS_KEY] = events.slice(-maxEventsPerQueue);
                }
            });
        }
    },

    /**
     * Clears an event queue for a topic
     * @param {String} topic defines the Figaro "topic" queue that should be cleared
     */
    resetTopicQueue: function resetTopicQueue(topic) {
        if (_eventQueue.eventQueues[topic]) {
            _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY] = null;
        }
    },

    /**
     * Resets the retry attempt counter for a topic, called when a send for that topic is successful
     * @param {String} topic defines the Figaro "topic" queue whose counter should be cleared
     */
    resetTopicRetryAttempts: function resetTopicRetryAttempts(topic) {
        if (_eventQueue.eventQueues[topic]) {
            _eventQueue.eventQueues[topic].retryAttempts = 0;
        }
    },

    /**
     * Increments the retry attempt counter for a topic, called when a send for that topic results in a 5XX response
     * Sets the next send time for the topic according to an exponential backoff strategy
     * @param {Object} A config for the Figaro "topic" queue whose counter should be incremented
     * @returns {Promise}
     */
    scheduleNextTopicRetryAttempt: function scheduleNextTopicRetryAttempt(topicConfig) {
        var topic = topicConfig.topic();
        if (_eventQueue.eventQueues[topic] && this.postIntervalEnabled) {
            return topicConfig.value('postFrequency').then(function (postFrequency) {
                var topicEventQueue = _eventQueue.eventQueues[topic];
                topicEventQueue.retryAttempts = topicEventQueue.retryAttempts || 0;
                topicEventQueue.retryAttempts++;

                var nextSendTime =
                    Math.pow(CONSTANTS.RETRY_EXPONENT_BASE, topicEventQueue.retryAttempts) * postFrequency;
                _eventQueue.resetTopicPostInterval(topic);
                _eventQueue.setTopicPostInterval(topicConfig, nextSendTime);
            });
        } else {
            return Promise.resolve();
        }
    },

    /**
     * Send queued events to the ingestion server
     * If a particular topic send has previously failed, RETRY_BACKOFF_SKIP_COUNT_KEY will be nonzero, indicating we should skip sending that number of times
     * @param {String} sendMethod "image" or "ajax" (default) or "ajaxSynchronous"
     * @param {Boolean} postNow will be true when clients force a send outside of the regular postFrequency interval
     * @returns {Promise}
     */
    sendEvents: function sendEvents(sendMethod, postNow) {
        var sendingTasks = [];
        for (var topic in _eventQueue.eventQueues) {
            var topicConfig = _eventQueue.eventQueues[topic].topicConfig;
            var sendingPromise = _eventQueue.sendEventsForTopicConfig(topicConfig, sendMethod, postNow);
            sendingTasks.push(sendingPromise);
        }

        return Promise.all(sendingTasks);
    },

    /**
     * Send events for a single topic queue
     * @param {Object} topicConfig defines the Figaro "topic" queue
     * @param {String} sendMethod "image" or "ajax" (default) or "ajaxSynchronous"
     * @param {Boolean} postNow will be true when clients force a send outside of the regular postFrequency interval
     * @returns {Promise}
     */
    sendEventsForTopicConfig: function sendEventsForTopicConfig(topicConfig, sendMethod, postNow) {
        var topic = topicConfig.topic();
        var topicQueue = _eventQueue.eventQueues[topic];

        return Promise.all([
            topicConfig.value('testExponentialBackoff'),
            topicConfig.value('metricsUrl'),
            topicConfig.disabled(),
            topicConfig.value('postFrequency')
        ]).then(function (outputs) {
            var testExponentialBackoff = outputs[0];
            var metricsUrl = outputs[1];
            var topicDisabled = outputs[2];
            var postFrequency = outputs[3];

            if (topicQueue && metricsUrl && !topicDisabled && !testExponentialBackoff) {
                // Do not send if we are trying to postNow in the middle of a backoff
                if (!(topicQueue.retryAttempts && postNow)) {
                    // The rule is "we post every postFrequency milliseconds", so even if it's been less than that (e.g. postNow), we reset
                    _eventQueue.resetTopicPostInterval(topic);
                    _eventQueue.setTopicPostInterval(topicConfig, postFrequency);
                    var sendingPromise;

                    switch (sendMethod) {
                        case CONSTANTS.SEND_METHOD.IMAGE:
                            sendingPromise = _eventQueue.sendEventsViaImage(topicConfig);
                            break;
                        case CONSTANTS.SEND_METHOD.BEACON:
                            sendingPromise = _eventQueue.sendEventsViaBeacon(topicConfig);
                            break;
                        case CONSTANTS.SEND_METHOD.AJAX_SYNCHRONOUS:
                            sendingPromise = _eventQueue.sendEventsViaAjax(topicConfig, false);
                            break;
                        case CONSTANTS.SEND_METHOD.AJAX: /* falls through */
                        default:
                            sendingPromise = _eventQueue.sendEventsViaAjax(topicConfig, true);
                            break;
                    }

                    return sendingPromise;
                }
            }
            // Fail automatically if test flag present
            else if (testExponentialBackoff) {
                return _eventQueue.scheduleNextTopicRetryAttempt(topicConfig);
            }
        });
    },

    /**
     * Makes one image ping per event in a queue of events, then clears the queue
     * This is typically called on page / app close when the JS context is about to disappear and thus we will not know if the events made it to the server
     * Current testing shows that browsers support 100+ image pings sent onpagehide, but we may need to alter our approach if this becomes unreliable
     * (For example, we could send multiple events in a single ping instead, but there might be URL length issues in IE)
     * @param {Object} topicConfig a config instance for the Figaro "topic" to send to
     * @returns {Promise}
     */
    sendEventsViaImage: function sendEventsViaImage(topicConfig) {
        var topic = topicConfig.topic();
        var returnedPromise = Promise.resolve();

        if (_eventQueue.eventQueues[topic]) {
            returnedPromise = resolveTopicConfigWithCallback(topicConfig, function (resolvedTopicConfig) {
                var topicUrl = resolvedTopicConfig.metricsUrl;
                var qpSeparator = topicUrl.indexOf('?') == -1 ? '?' : '&';
                var imageBaseUrl = topicUrl + qpSeparator + 'responseType=image';
                var events = _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY];

                if (events && events.length) {
                    events.forEach(function (event) {
                        var imageParams = _eventQueue.createQueryParams(event);
                        if (imageParams) {
                            var imgUrl = imageBaseUrl + '&' + imageParams;
                            var imgObject = new Image();
                            var properties = _eventQueue.eventQueues[topic][CONSTANTS.PROPERTIES_KEY];
                            if (properties && properties.anonymous) {
                                imgObject.setAttribute('crossOrigin', 'anonymous');
                            }
                            imgObject.src = imgUrl;
                        }
                    });
                }

                _eventQueue.resetTopicQueue(topic);
            });
        }
        return returnedPromise;
    },

    /**
     * Convert an event object into a query parameter string, without a leading separator
     * Guaranteed to return "null" if there are no event fields
     * @param {Object} event key/value pairs containing event data
     */
    createQueryParams: function createQueryParams(event) {
        var val;
        var stringVal;
        var returnValue = '';
        Object.keys(event).forEach(function (key, index, eventKeys) {
            val = event[key];
            // do not double-encode strings otherwise they will be reported as: '<value>'
            stringVal = reflect.isString(val) ? val : JSON.stringify(val);
            returnValue += key + '=' + encodeURIComponent(stringVal);
            if (index < eventKeys.length - 1) {
                // don't add a trailing ampersand
                returnValue += '&';
            }
        });
        return returnValue.length ? returnValue : null;
    },

    /**
     * Makes one AJAX request per topic and clears the queue for that topic on success
     * If any queue fails, retry using an exponential backoff strategy for that queue
     * Refer to Metrics documentation for more details
     * @param {Object} topicConfig a config instance for the Figaro "topic" to send to
     * @param {Boolean} async - send asynchronously
     * @returns {Promise}
     */
    sendEventsViaAjax: function sendEventsViaAjax(topicConfig, async) {
        var returnedPromise = Promise.resolve();
        var topic = topicConfig.topic();
        if (_eventQueue.eventQueues[topic] && _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY]) {
            // Store events to be sent and reset the queue
            var events = _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY];
            var jsonEventsString = enrichAndSerializeEvents(events);
            _eventQueue.resetTopicQueue(topic);

            if (jsonEventsString) {
                returnedPromise = resolveTopicConfigWithCallback(topicConfig, function (resolvedTopicConfig) {
                    var topicUrl = resolvedTopicConfig.metricsUrl;
                    var requestTimeout = resolvedTopicConfig.requestTimeout;
                    var resetRetryAttempts = function resetRetryAttempts() {
                        _eventQueue.resetTopicRetryAttempts(topic);
                    };
                    var onAjaxFailure = function onAjaxFailure(error, statusCode) {
                        // We're being told not to keep resending these events.
                        if (statusCode >= 400 && statusCode < 500) {
                            resetRetryAttempts();
                        } else {
                            // Prepend the events that failed to send back onto the queue
                            var newEvents = _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY] || [];
                            _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY] = events.concat(newEvents);

                            _eventQueue.scheduleNextTopicRetryAttempt(topicConfig);
                        }
                    };
                    var eventQueueProps = _eventQueue.eventQueues[topic][CONSTANTS.PROPERTIES_KEY] || {};
                    var options = {
                        async: async,
                        timeout: requestTimeout
                    };

                    if (eventQueueProps.anonymous) {
                        options.withCredentials = false;
                    }
                    network.makeAjaxRequest(topicUrl, 'POST', jsonEventsString, resetRetryAttempts, onAjaxFailure, options);
                });
            }
        }
        return returnedPromise;
    },

    /**
     * Makes an HTTP POST request via navigator.sendBeacon() if it is in the environment.
     * Note: The sendBeacon() method returns true if the user agent successfully queued the data for transfer, otherwise false.
     *       sendBeacon() always includes credentials, so we fallback to the IMAGE/AJAX_SYNCHRONOUS methods to handle the anonymous use case.
     *       While testing out possible failures of sendBeacon(), the only 2 cases we encountered was using a non-"simple" content type like "application/json",
     *       or by passing data that is too large. Both cases would lead to failures when retrying, so retrying logic has intentionally been omitted in this approach.
     * @param {Object} topicConfig a config instance for the Figaro "topic" to send to
     */
    sendEventsViaBeacon: function sendEventsViaBeacon(topicConfig) {
        var sendPromise = Promise.resolve();

        if (!reflect.isFunction(navigator.sendBeacon)) {
            _logger().error('navigator.sendBeacon() is not available in the environment');
            return sendPromise;
        }

        var topic = topicConfig.topic();
        var topicQueue = _eventQueue.eventQueues[topic];

        if (topicQueue) {
            var eventQueueProps = topicQueue[CONSTANTS.PROPERTIES_KEY];

            // Fallback to other send methods to handle the anonymous use case
            if (eventQueueProps && eventQueueProps.anonymous) {
                // using fetch with keepalive to send events to fix the large event content issue (impressions field).
                if (_isFetchAndKeepaliveAvailable()) {
                    sendPromise = _eventQueue.sendEventsViaFetch(topicConfig, { keepalive: true });
                } else if (_isIOS()) {
                    // iOS browsers do not allow image pings to send onpagehide; use (deprecated) synchronous AJAX in those browsers
                    sendPromise = _eventQueue.sendEventsViaAjax(topicConfig, false);
                } else {
                    sendPromise = _eventQueue.sendEventsViaImage(topicConfig);
                }
            } else {
                var jsonEventsString = enrichAndSerializeEvents(topicQueue[CONSTANTS.EVENTS_KEY]);
                if (jsonEventsString) {
                    _eventQueue.resetTopicQueue(topic);

                    sendPromise = resolveTopicConfigWithCallback(topicConfig, function (resolvedTopicConfig) {
                        var topicUrl = resolvedTopicConfig.metricsUrl;
                        var Blob = environment.globalScope().Blob;
                        var eventsBlob = new Blob([jsonEventsString], { type: 'application/json' });
                        var beaconResponse = navigator.sendBeacon(topicUrl, eventsBlob);

                        if (!beaconResponse) {
                            _logger().error('navigator.sendBeacon() was unable to queue the data for transfer');
                        }
                    });
                }
            }
        }

        return sendPromise;
    },

    /**
     * Makes an HTTP POST request via fetch()
     * @param {Object} topicConfig a config instance for the Figaro "topic" to send to
     * @param {Object} options an object contains the options of fetch API
     * @param {Boolean} options.keepalive whether allow the request to outlive the page
     */
    sendEventsViaFetch: function sendEventsViaFetch(topicConfig, options) {
        var sendPromise = Promise.resolve();
        var topic = topicConfig.topic();
        var topicQueue = _eventQueue.eventQueues[topic];
        var keepalive = reflect.isDefinedNonNull(options) ? options.keepalive : null;

        if (reflect.isDefinedNonNull(topicQueue)) {
            var jsonEventsString = enrichAndSerializeEvents(topicQueue[CONSTANTS.EVENTS_KEY]);
            if (jsonEventsString) {
                _eventQueue.resetTopicQueue(topic);

                var eventQueueProps = topicQueue[CONSTANTS.PROPERTIES_KEY] || {};
                sendPromise = resolveTopicConfigWithCallback(topicConfig, function (resolvedTopicConfig) {
                    var topicUrl = resolvedTopicConfig.metricsUrl;
                    reflect.globalScope().fetch(topicUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: jsonEventsString,
                        credentials: eventQueueProps.anonymous === true ? 'omit' : 'same-origin',
                        keepalive: reflect.isDefinedNonNull(keepalive) ? keepalive : true
                    });
                });
            }
        }
        return sendPromise;
    },

    /**
     * If no postInterval is currently set, sets postInterval to "postInterval"
     * Note: Currently, only _sendEvents calls this function, but in the future, if other callers wanted to set a new interval due to, say, a config change,
     *       then events enqueued under the old postFrequency time will now have to wait (or be expedited) to the new time. To fix this, when any old
     *       interval fires, the callback can check to see if the interval passed in is different than _eventQueue.postIntervalToken and if so, it will tear down its timer.
     * @param {Object} topic config
     * @param {int} postInterval in ms
     */
    setTopicPostInterval: function setTopicPostInterval(topicConfig, postInterval) {
        var topic = topicConfig.topic();
        if (_eventQueue.eventQueues[topic] && postInterval && this.postIntervalEnabled) {
            this.resetTopicPostInterval(topic);
            _eventQueue.eventQueues[topic].postIntervalToken = environment
                .globalScope()
                .setInterval(function onPostIntervalTrigger() {
                    _logger().debug(
                        'MetricsKit: triggering postIntervalTimer for ' + topic + ' at ' + new Date().toString()
                    );
                    _eventQueue.sendEventsForTopicConfig(topicConfig);
                }, postInterval);
        }
    },

    resetTopicPostInterval: function resetTopicPostInterval(topic) {
        if (_eventQueue.eventQueues[topic]) {
            environment.globalScope().clearInterval(_eventQueue.eventQueues[topic].postIntervalToken);
            _eventQueue.eventQueues[topic].postIntervalToken = null;
        }
    },

    resetQueuePostIntervals: function resetQueuePostIntervals() {
        for (var topic in _eventQueue.eventQueues) {
            _eventQueue.resetTopicPostInterval(topic);
        }
    },

    setQueuePostIntervals: function setQueuePostIntervals() {
        var tasks = [];
        var setTopicPostIntervalFn = function (topicConfig) {
            return function (postFrequency) {
                _eventQueue.setTopicPostInterval(topicConfig, postFrequency);
            };
        };
        for (var topic in _eventQueue.eventQueues) {
            var events = _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY];
            var topicConfig = _eventQueue.eventQueues[topic].topicConfig;
            if (events && events.length) {
                var taskPromise = topicConfig.value('postFrequency').then(setTopicPostIntervalFn(topicConfig));
                tasks.push(taskPromise);
            }
        }
        return Promise.all(tasks);
    },

    /**
     * Determines whether the object contains the provided value.
     * Note that values that are functions will be ignored.
     * @param {Object} object the object whose values will be evaluated
     * @param {Any} value the requested value to search for on the provided object
     * @returns {Boolean} whether the object contains the value
     * TODO: consider moving to utils
     */
    objectContainsValue: function objectContainsValue(object, value) {
        var result = false;
        for (var property in object) {
            var aValue = object[property];
            if (object.hasOwnProperty(property) && !reflect.isFunction(aValue) && aValue === value) {
                result = true;
                break;
            }
        }
        return result;
    },

    /**
     * Set event queue related properties for the giving topic
     * @param {String} topic defines the Figaro "topic" that this event should be stored under
     * @param {Object} properties the event queue properties for the topic
     * @param {Boolean} properties.anonymous true if sending all events for the topic with credentials omitted(no cookies, no PII fields)
     */
    setProperties: function setProperties(topic, properties) {
        _eventQueue.eventQueues = _eventQueue.eventQueues || {};
        _eventQueue.eventQueues[topic] = _eventQueue.eventQueues[topic] || {};
        _eventQueue.eventQueues[topic][CONSTANTS.PROPERTIES_KEY] = properties;
    }
};

/**
 ************************************ PSEUDO-PRIVATE METHODS/IVARS ************************************
 * These functions need to be accessible for ease of testing, but should not be used by clients
 */
function _utQueue() {
    return _eventQueue;
}

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Adds all the supplemental fields like "postTime", etc.
 * Guaranteed to return "null" if there are no events
 * @param {Array} eventQueue a list of events to send
 * @return A stringified version of our eventQueue as a batch, including supplementary top-level fields, all ready to deliver in a ping
 */
function enrichAndSerializeEvents(eventQueue) {
    var eventsBatchString = null;

    if (eventQueue && eventQueue.length) {
        var eventsDict = {};
        eventsDict['deliveryVersion'] = CONSTANTS.EVENT_DELIVERY_VERSION;
        eventsDict['postTime'] = Date.now();
        eventsDict[CONSTANTS.EVENTS_KEY] = eventQueue;
        try {
            eventsBatchString = JSON.stringify(eventsDict);
        } catch (e) {
            _logger().error('Error stringifying events as JSON: ' + e);
        }
    }
    return eventsBatchString;
}

function enrichAndSerializeEvent(event) {
    return enrichAndSerializeEvents([event]);
}

/**
 * @param {Object} topicConfig instance
 * @return {Promise} a Promise that returns the metrics URL for this topic
 */
function metricsUrlForConfig(topicConfig) {
    return topicConfig.value('metricsUrl').then(function (metricsUrl) {
        var baseMetricsUrl = metricsUrl + '/' + CONSTANTS.URL_DELIVERY_VERSION + '/';
        return baseMetricsUrl + topicConfig.topic();
    });
}

/**
 * This method is used to hide the topicConfig.value implementation for multiple properties, in order to support async and sync logic in sendEventsViaAjax().
 * @param {Object} topicConfig an instance of TopicConfig(with a method named "value" and returns Promise from it) or an object that contains the "metricsUrl" and "topic()" properties
 * @param {Function} callback a function to invoke with an object has metricsUrl, requestTimeout
 */
function resolveTopicConfigWithCallback(topicConfig, callback) {
    if (!reflect.isFunction(callback)) {
        _logger().warn('No callback function is provided for resolveTopicConfigWithCallback()');
        return;
    }

    if (reflect.isString(topicConfig.metricsUrl) && !reflect.isFunction(topicConfig.value)) {
        var topic = reflect.isFunction(topicConfig.topic) ? topicConfig.topic() : topicConfig.topic;
        var metricsUrl = topicConfig.metricsUrl + '/' + CONSTANTS.URL_DELIVERY_VERSION + '/' + topic;
        var requestTimeout = topicConfig.requestTimeout || CONSTANTS.DEFAULT_REQUEST_TIMEOUT;
        var postFrequency = topicConfig.postFrequency;

        return callback({
            requestTimeout: Math.min(requestTimeout, postFrequency),
            metricsUrl: metricsUrl
        });
    } else {
        return Promise.all([
            topicConfig.value('requestTimeout'),
            topicConfig.value('postFrequency'),
            metricsUrlForConfig(topicConfig)
        ]).then(function (outputs) {
            var requestTimeout = outputs[0] || CONSTANTS.DEFAULT_REQUEST_TIMEOUT;
            var postFrequency = outputs[1];
            var metricsUrl = outputs[2];
            return callback({
                requestTimeout: Math.min(requestTimeout, postFrequency),
                metricsUrl: metricsUrl
            });
        });
    }
}

/**
 * @param {Object} topicConfig instance
 * @return {Promise} a Promise that returns the request timeout for this config
 * Defaults to CONSTANTS.DEFAULT_REQUEST_TIMEOUT
 */
function requestTimeoutForConfig(topicConfig) {
    return Promise.all([topicConfig.value('requestTimeout'), topicConfig.value('postFrequency')]).then(function (
        outputs
    ) {
        var requestTimeout = outputs[0] || CONSTANTS.DEFAULT_REQUEST_TIMEOUT;
        var postFrequency = outputs[1];
        return Math.min(requestTimeout, postFrequency);
    });
}

/**
 * Determines whether events will be sent via a post interval.
 * If this value is false then the client must perform flushing manually and events will not be scheduled or sent automatically.
 * @param {Bool} enabled whether the postInterval is enabled or not
 * @returns {Promise}
 */
function setPostIntervalEnabled(enabled) {
    _eventQueue.postIntervalEnabled = enabled;
    if (enabled) {
        return _eventQueue.setQueuePostIntervals();
    } else {
        return Promise.resolve(_eventQueue.resetQueuePostIntervals());
    }
}

/**
 * Enqueues events to be sent to the server in batches after "postFrequency" milliseconds since the previous send.
 * The queue is stored in memory, and will retry on failed sends for as long as the session is open.
 * Immediately before a page turn/tab close (usually onpagehide), clients can call flushUnreportedEvents() to send up any events still left in the queue.
 *
 * Flow:
 *      1. Normal:
 *          a. [recordEvent()} Events posted to in-memory eventQueue via "recordEvent() (this method)".
 *             NOTE1: Only remember the most recent MAX_PERSISTENT_QUEUE_SIZE events per queue so we don't eat up all browser memory if we can't send for a very long time.
 *             NOTE2: We could have another set of "waitingForAck" queues which was also in-memory, but then
 *                    we'd need code to merge two queues on re-tries (since _sendEvents() already merges in previously-queued events before attempting to [re]send)
 *                    Since the send failure case is a rare case anyway, we err on the side of not adding code complexity to deal with it.
 *          b. [_sendEvents()] Wait "_postFrequency()" milliseconds before attempting actual "_sendEvents()"
 *          c. Set a timeout for the send which should be the lower of "_postFrquency()" or config.requestTimeout (which defaults to DEFAULT_REQUEST_TIMEOUT).
 *             This guarantees that only one send attempt per topic is pending at any given time.
 *          d. Wait for status=200 response ack, and clear event queue when received (see "Edge Cases", below)
 *      2. Unsent due to ingestion server problem (5XX response):
 *          a. Continue gathering events, adding to in-memory eventQueue
 *          b. Use an exponential back-off strategy by waiting 2^1 = times "_postFrequency()" milliseconds before attempting another "_sendEvents()", as in "Normal" case, above
 *          c. If the ingestion server responds with another 5XX code, wait 2^2 = 4 times "_postFrequency()" milliseconds before attempting another send, and so on
 *          d. Continue as in 1c, above
 *      3. Unsent due to failed conection or other error:
 *          a. Continue gathering events, adding to in-memory eventQueue
 *          b. Wait "_postFrequency()" milliseconds before attempting another "_sendEvents()", as in "Normal" case, above
 *          c. Continue as in 1c, above
 *
 * Edge Cases: Here are the small edge-case windows of failure in the in-memory event queue facility:
 *          1. If two batches of events are sent out before the first one returns and clears the queue, the second one will try to send any queued events as well.
 *             For this to happen, we'd have to be in a situation where we're not leaving the page, event sends are taking some time to respond,
 *             causing us to build up a queue, and then two "sends" are attempted back-to-back by a client calling recordEvent() with postNow=true or flushUnreportedEvents().
 *             It's so rare that the code complexity to try and prevent this case is not worth it (synchronous event posting is the most straightforward way to handle it).
 *          2. If we send a batch of events, the last of which causes, say, a page turn, and invokes flushUnreportedEvents(), we will never get the ack that the batch made it to the server
 *             so we just clear the queue and assume that they made it. During empirical testing, events did continue to get sent event after the browser is closed as long as there is a network connection.
 *          3. If the ingestion server is down, we would only retry as long as the session is open, and lose all events once the user leaves. Events are usually flushed on page turns
 *             without the opportunity to see if the send was successful (see 2 above) so if we wanted to preserve events in the case of ingestion server failure,
 *             we would have to a) keep track of the previous send attempts, b) not flush events on page turn, c) stash the events and the retry state in persistent storage,
 *             and d) fetch the events from persistent storage and restore the retry state, which we choose not to do in order to avoid all of this complexity for what is probably a rare scenario.
 *
 * Note: each topic has its own queue, and all of the above logic applies to each individual queue.
 * For example, exponential backoff works independently on a per-topic basis, in case the server tells us to back off of one topic, but not another.
 * Testing tips:
 * 1) A debug message is logged every time a postInterval timer is triggered, but the metricskit logger debug messages are off by default.
 *    They can be enabled in Web inspector via: metrics.system.logger.setLevel(metrics.system.logger.DEBUG);
 * 2) Exponential backoff can be tested by using a debug source with the 'testExpontentialBackoff' flag enabled.
 *    When this flag is enabled, the metrics queue will skip sending and instead schedule the next retry for _postFrequency() * RETRY_EXPONENT_BASE ^ n milliseconds
 *    where n is the current retry attempt. (see mt-metricskit docs for more details on using debug sources)
 *    To see this in action, you can enable debug logs as in (1) above, then set a debug source with testExponentialBackoff=true (and optionally, a lower postFrequency),
 *    then call recordEvent() to enqueue an event.
 *    You should see a debug message (which includes a timestamp) after postFrequency milliseconds, and then every postFrequency * 2^n milliseconds thereafter.
 *
 * @param {Object} topicConfig - a instance of Config class(mt-client-config) which contains the topic defined the Figaro "topic" that this event should be stored under
 * @param {Object} eventFields a JavaScript object which will be converted to a JSON string and enqued for sending to Figaro according to the postFrequency schedule
 * @param {Boolean} postNow - effectively forces an immediate send, along with any other messages that may be sitting in the queue
 * @returns {Promise}
 */
function recordEvent(topicConfig, eventFields, postNow) {
    var topic = topicConfig.topic();

    return topicConfig.disabled().then(function (disabled) {
        if (!disabled) {
            return topicConfig
                .value('postFrequency')
                .then(function (postFrequency) {
                    if (postFrequency === 0) {
                        postNow = true;
                    }
                    // The "pagehide" event was tested and works reliably, so we only need to keep the queue in memory, and expect clients to clear the queue on app close
                    return _eventQueue.enqueueEvent(topicConfig, eventFields).then(function () {
                        return postFrequency;
                    });
                })
                .then(function (postFrequency) {
                    if (postNow) {
                        return _eventQueue.sendEvents(CONSTANTS.SEND_METHOD.AJAX, true);
                    } else if (!_eventQueue.eventQueues[topic].postIntervalToken && _eventQueue.postIntervalEnabled) {
                        // Schedule the next send if the timer isn't already running
                        _eventQueue.setTopicPostInterval(topicConfig, postFrequency);
                    }
                });
        }
    });
}

/**
 * Sends any remaining events in the queue, then clears it.
 * Events will be sent as individual image pings or as synchronous AJAX requests for iOS (these are the only send methods that actually
 * get through during a pagehide event). We expect clients to call this function before the app closes in order to clear the event queues,
 * otherwise any remaining events will be lost. We could theoretically add our own event listener so this call happens automatically,
 * but single page apps could be using history.pushState which triggers onpagehide, and in those cases they would not
 * need to flush until the app is actually closing.
 * Note: This is typically called on page / app close when the JS context is about to disappear and thus we will not know if the events made it to the server
 * @param {Boolean} appIsExiting - Pass true if events are being flushed due to your app exiting or page going away
 * (the send method will be different in order to attempt to post events prior to actual termination)
 * @param {String} appExitSendMethod (optional) the send method for how events will be flushed when the app is exiting.
 * Possible options are enumerated in the `eventRecorder.SEND_METHOD` object.
 * Note: This argument will be ignored if appIsExiting is false.
 * @returns {Promise}
 */
function flushUnreportedEvents(appIsExiting, appExitSendMethod) {
    if (appIsExiting) {
        if (appExitSendMethod === SEND_METHOD.BEACON_SYNCHRONOUS) {
            return flushUnreportedEventsSynchronously();
        }
        if (reflect.isString(appExitSendMethod) && _eventQueue.objectContainsValue(SEND_METHOD, appExitSendMethod)) {
            return _eventQueue.sendEvents(appExitSendMethod, true);
        } else if (reflect.isFunction(navigator.sendBeacon)) {
            return _eventQueue.sendEvents(CONSTANTS.SEND_METHOD.BEACON, true);
        } else {
            // iOS browsers do not allow image pings to send onpagehide; use (deprecated) synchronous AJAX in those browsers
            if (_isIOS()) {
                return _eventQueue.sendEvents(CONSTANTS.SEND_METHOD.AJAX_SYNCHRONOUS, true);
            } else {
                return _eventQueue.sendEvents(CONSTANTS.SEND_METHOD.IMAGE, true);
            }
        }
    } else {
        return _eventQueue.sendEvents(CONSTANTS.SEND_METHOD.AJAX, true);
    }
}

function flushUnreportedEventsSynchronously() {
    for (var topic in _eventQueue.eventQueues) {
        var topicQueue = _eventQueue.eventQueues[topic];
        var flushConfig = topicQueue.flushConfig;
        var resolvedTopicConfig = reflect.extend({}, flushConfig, {
            _topic: topic,
            topic: function () {
                return this._topic;
            }
        });

        _eventQueue.sendEventsViaBeacon(resolvedTopicConfig);
    }
}

/*
 *  src/event_recorder.js
 *  mt-event-queue
 *
 *  Copyright © 2016-2017 Apple Inc. All rights reserved.
 *
 */

/**
 * Provides a pre-built delegate to use against the metrics.system.eventRecorder delegate via metrics.system.eventRecorder.setDelegate()
 * If you want to use *most* of these methods, but not *all* of them, you can set this delegate and then create your own with whichever few methods you need to
 * customize additionally, and then setDelegate() *that* delegate, in order to override those methods.
 * @constructor
 * @param {Object} kit An object that implements the Kit interface
 */
var QueuedEventRecorder = function QueuedEventRecorder(kit) {
    Base.apply(this, arguments);
};

QueuedEventRecorder.prototype = Object.create(Base.prototype);

QueuedEventRecorder.prototype.constructor = QueuedEventRecorder;

/**
 ************************************ PSEUDO-PRIVATE METHODS/IVARS ************************************
 * These functions need to be accessible for ease of testing, but should not be used by clients
 */

QueuedEventRecorder.prototype._utResetQueue = function _utResetQueue() {
    for (var topic in _utQueue().eventQueues) {
        _utQueue().resetTopicPostInterval(topic);
    }
    _utQueue().eventQueues = {};
};

/**
 * An implementation of _record method in the parent class.
 * @param {Object} topicConfig a config instance for the Figaro "topic" to send to
 * @param {Object} eventFields a JavaScript object which will be converted to a JSON string and enqued for sending to Figaro according to the postFrequency schedule.
 * @param {Boolean} postNow - effectively forces an immediate send, along with any other messages that may be sitting in the queue
 * @returns {Promise}
 */
QueuedEventRecorder.prototype._record = function record(topicConfig, eventFields, postNow) {
    return recordEvent(topicConfig, eventFields, postNow);
};

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

QueuedEventRecorder.prototype.SEND_METHOD = SEND_METHOD;

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
QueuedEventRecorder.prototype.setDelegate = function setDelegate(delegate) {
    return reflect.attachDelegate(this, delegate);
};

/**
 * Sends any remaining events in the queue, then clears it
 * This is typically called on page / app close when the JS context is about to disappear and thus we will
 * not know if the events made it to the server
 * @param {Boolean} appIsExiting - Pass true if events are being flushed due to your app exiting or page going away
 * (the send method will be different in order to attempt to post events prior to actual termination)
 * @param {String} appExitSendMethod (optional) the send method for how events will be flushed when the app is exiting.
 * Possible options are enumerated in the `eventRecorder.SEND_METHOD` object.
 * Note: This argument will be ignored if appIsExiting is false.
 * @returns {Promise}
 */
QueuedEventRecorder.prototype.flushUnreportedEvents = function flushUnreportedEvents$1(appIsExiting, appExitSendMethod) {
    return flushUnreportedEvents.apply(null, arguments);
};

/**
 * Set event queue related properties for the giving topic
 * @param {String} topic defines the Figaro "topic" that this event should be stored under
 * @param {Object} properties the event queue properties for the topic
 * @param {Boolean} properties.anonymous true if sending all events for the topic with credentials omitted(no cookies, no PII fields)
 */
QueuedEventRecorder.prototype.setProperties = function setProperties(topic, properties) {
    Object.getPrototypeOf(QueuedEventRecorder.prototype).setProperties.call(this, topic, properties);
    _utQueue().setProperties(topic, properties);
};

/**
 * An implementation of cleanup method in the parent class.
 */
QueuedEventRecorder.prototype.cleanup = function cleanup() {
    Object.getPrototypeOf(QueuedEventRecorder.prototype).cleanup.call(this);
    this._utResetQueue();
};

/*
 *  src/immediate_event_recorder.js
 *  mt-event-queue
 *
 *  Copyright © 2016-2019 Apple Inc. All rights reserved.
 *
 */

/**
 * Provides a pre-built delegate to use against the metrics.system.eventRecorder delegate via metrics.system.eventRecorder.setDelegate()
 * If you want to use *most* of these methods, but not *all* of them, you can set this delegate and then create your own with whichever few methods you need to
 * customize additionally, and then setDelegate() *that* delegate, in order to override those methods.
 * @constructor
 * @param {Object} kit An object that implements the Kit interface
 */
var ImmediateEventRecorder = function ImmediateEventRecorder(kit) {
    Base.apply(this, arguments);
};

ImmediateEventRecorder.prototype = Object.create(Base.prototype);
ImmediateEventRecorder.prototype.constructor = ImmediateEventRecorder;

/**
 ************************************ PRIVATE METHODS/IVARS ************************************
 */

/**
 * An implementation of _record method in the parent class.
 * @param {Object} topicConfig a config instance for the Figaro "topic" to send to
 * @param eventFields
 * @returns {Promise}
 */
ImmediateEventRecorder.prototype._record = function record(topicConfig, eventFields) {
    var jsonEventsString = enrichAndSerializeEvent(eventFields);
    if (jsonEventsString) {
        return Promise.all([metricsUrlForConfig(topicConfig), requestTimeoutForConfig(topicConfig)]).then(
            function (outputs) {
                var topicUrl = outputs[0];
                var requestTimeout = outputs[1];
                var options = { timeout: requestTimeout };
                if (
                    this._topicPropsCache[topicConfig.topic()] &&
                    this._topicPropsCache[topicConfig.topic()].anonymous
                ) {
                    options.withCredentials = false;
                }
                network.makeAjaxRequest(topicUrl, 'POST', jsonEventsString, null, null, options);
            }.bind(this)
        );
    }
};

/*
 *  mt-event-queue/index.js
 *  mt-event-queue
 *
 *  Copyright © 2016-2017 Apple Inc. All rights reserved.
 *
 */

var logger = /*#__PURE__*/ loggerNamed('mt-event-queue');

export { QueuedEventRecorder as EventRecorder, ImmediateEventRecorder, environment, logger, network, setPostIntervalEnabled as setEventQueuePostIntervalEnabled };
