import { storage, reflect, network, keyValue, number } from '@amp-metrics/mt-metricskit-utils-private';
import Logger from '@amp-metrics/mt-client-logger-core';

/*
 *  src/environment.js
 *  mt-client-config
 *
 *  Copyright © 2016-2017 Apple Inc. All rights reserved.
 *
 */

/**
 * Provides a set of environment-specific (platform-specific) functions which can be individually overridden for the needs
 * of the particular environment, or replaced en masse by providing a single replacement environment delegate object
 * The functionality in this class is typically replaced via a delegate.
 * @see setDelegate
 * @delegatable
 * @constructor
 */
var Environment = function () {};

/**
 ************************************ 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.
 */
Environment.prototype.setDelegate = function setDelegate(delegate) {
    return reflect.attachDelegate(this, delegate);
};

Environment.prototype.localStorageObject = storage.localStorageObject;
Environment.prototype.sessionStorageObject = storage.sessionStorageObject;

/*
 *  src/network.js
 *  mt-client-config
 *
 *  Copyright © 2018 Apple Inc. All rights reserved.
 *
 */

/**
 * Network request methods exposed so delegate callers can override
 * @constructor
 */
var Network = function () {};

/**
 * 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.
 */
Network.prototype.setDelegate = function setDelegate(delegate) {
    return reflect.attachDelegate(this, delegate);
};

/**
 * Covers private utils implementation of makeAjaxRequest for delegation
 */
Network.prototype.makeAjaxRequest = network.makeAjaxRequest;

/*
 *  src/config.js
 *  mt-client-config
 *
 *  Copyright © 2016-2017 Apple Inc. All rights reserved.
 *
 */

var NO_TOPIC_KEY = 'noTopicConfig';
var COMPOUND_SEPARATOR = '_';

/**
 * The default config should not include keys which have meaning if they are omitted.
 * For example, a configSource without impressions means no impressions should be recorded, and in this case we should
 * not have impressions in defaults so we don't inadvertently disobey the client's configSource.
 */
var DEFAULTS = {
    configBaseUrl: 'https://xp.apple.com/config/1/report',
    disabled: true // Prevent sending event if no config is available
};

// @private
var _defaultConfig;

/**
 * Appends the provided source and its subsection if the subsection key matches the provided topic to the provided configSources array.
 * @param {Array} configSources
 * @param {String} topic
 * @param {Object} source
 */
var _appendSectionAndSubsectionToConfigSources = function _appendSectionAndSubsectionToConfigSources(
    configSources,
    topic,
    source
) {
    if (source) {
        configSources.push(source);
        var subsection = source[topic];
        if (subsection && reflect.hasAnyKeys(subsection)) {
            configSources.push(subsection);
        }
    }
};

/**
 * Provides config-related functionality including managing config sources and values.
 * The functionality in this class is typically replaced via a delegate.
 * @see setDelegate
 * @delegatable
 * @constructor
 * @param {String} topic
 */
var Config = function Config(topic) {
    // @public
    this.environment = new Environment();

    /**
     * @public
     * @deprecated
     */
    this.network = new Network();

    // @public
    this.logger = /*#__PURE__*/ new Logger('mt-client-config');

    // @private
    this._topic = topic || NO_TOPIC_KEY;

    // @private
    this._debugSource = null;
    // @private
    this._cachedSource = null;
    // @private
    this._serviceSource = null;
    // @private
    this._initCalled = false;
    // @private
    this._initialized = false;
    // @private
    this._showedDebugWarning = false;
    // @private
    this._showedNoProvidedSourceWarning = false;
    // @private
    this._keyPathsThatSuppressWarning = {
        configBaseUrl: true // used to fetch a config source, so we do not expect sources to be set when retrieving this value
    };
    // @private
    this._configFetchPromise = null;

    // @const
    this.DEBUG_SOURCE_KEY = 'mtClientConfig_debugSource' + COMPOUND_SEPARATOR + this._topic;
    // @const
    this.CACHED_SOURCE_KEY = 'mtClientConfig_cachedSource' + COMPOUND_SEPARATOR + this._topic;
};

/**
 * @return {Config} the default config instance, which is not associated with any topic
 */
Config.defaultConfig = function defaultConfig() {
    if (!_defaultConfig) {
        _defaultConfig = new Config(NO_TOPIC_KEY);
    }
    return _defaultConfig;
};

/**
 ************************************ PSEUDO-PRIVATE METHODS/IVARS ************************************
 * These functions need to be accessible for ease of testing, but should not be used by clients
 */
Config.prototype._defaults = function _defaults() {
    return DEFAULTS;
};

Config.prototype._setInitialized = function _setInitialized(initialized) {
    this._initialized = initialized;
};

Config.prototype._setInitCalled = function _setInitCalled(initCalled) {
    this._initCalled = initCalled;
};

Config.prototype._setShowedDebugWarning = function _setShowedDebugWarning(value) {
    this._showedDebugWarning = value;
};

Config.prototype._setShowedNoProvidedSourceWarning = function _setShowedNoProvidedSourceWarning(value) {
    this._showedNoProvidedSourceWarning = value;
};

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

/**
 * 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.
 */
Config.prototype.setDelegate = function setDelegate(delegate) {
    return reflect.attachDelegate(this, delegate);
};

/**
 * Reset the attached delegates from
 * @param delegate
 */
Config.prototype.resetDelegate = function resetDelegate() {
    // reset the delegates from environment, network and logger
    reflect.detachMethods(this);
    // Detach the attached methods from prototype(source, debugSource and attached utility methods from mt-metricskit-utils-private, etc.) of the config instance
    reflect.resetDelegates(this);
};

/**
 * @return {String} the Figaro topic that this config corresponds with
 * Most clients do not need to override this method
 */
Config.prototype.topic = function topic() {
    return this._topic;
};

/**
 * Returns the metrics config endpoint hostname
 * Most clients do not need to override this method
 * @deprecated
 * @return {String} a hostname e.g.xp.apple.com
 */
Config.prototype.configHostname = function configHostname() {};

/**
 * Returns a constructed URL to the metrics config endpoint for use with getConfig()
 * Most clients do not need to override this method
 * @deprecated
 * @return {Promise} A Promise with a URL to the metrics config endpoint e.g. https://xp.apple.com/config/1/report/xp_its_main
 */
Config.prototype.configUrl = function configUrl() {
    var configHostname = this.configHostname();
    var returnUrlPromise;

    if (configHostname) {
        returnUrlPromise = Promise.resolve('https://' + configHostname + '/config/1/report');
    } else {
        returnUrlPromise = this.value('configBaseUrl');
    }

    return returnUrlPromise.then(
        function (returnUrl) {
            if (this._topic !== NO_TOPIC_KEY) {
                returnUrl += '/' + this.topic();
            } else {
                this.logger.error('config.configUrl(): Topic must be provided');
            }
            return returnUrl;
        }.bind(this)
    );
};

/**
 * This function will be used to access all of the sources for configuration data (e.g. disabled, blacklistedEvents, fieldsMap, etc.)
 * THIS METHOD MUST BE PROVIDED BY A DELEGATE
 * Returns an array of key/value objects (dictionaries) for all of the config sources (e.g. the bag, the page, the control parent, etc.).
 * This method will be called frequently and repeatedly from the metrics.config.* functions.
 * MetricsKit will use this return value to traverse the list of config objects, looking for config values.
 * If later dictionaries of key/value pairs contain any keys already collected, the most late (farthest in the area) config value will overwrite earlier ones.
 * IMPORTANT: This function might be called frequently and repeatedly so should be optimized for performance.
 *            It will be called frequently (rather than having this API provide a "setConfig" method for permanently setting the config values) since
 *            these config values can always be changing from one call to the next, so this ensures that they are current.
 * THEREFORE: This function should NOT try to "simplify" by, e.g., merging all config sources into a single object to return when called.
 *            Doing so is an enormous amount of work to do each time MetricsKit needs to look up a single value.
 *            It is far more efficient for MetricsKit to simply interogate each configSource for the required key, rather than
 *            the delegate function merging *all* keys of *all* sources (looping through all values of all sources) in order to look up a single value.
 * @example var sources = function() { return [itms.getBag().metrics, pageData.metrics.config]; };   // return an array of sources of app config
 * @example var sources = function() { return metrics.utils.keyValue.sourcesArray(itms.getBag().metrics, pageData.metrics.config, swooshData.metrics.config); }; // Let MetricsKit help build the array from a varargs list of sources
 * @example var sources = function() { return metrics.utils.keyValue.sourcesArray(existingArrayOfConfigSources, pageData.metrics.config, swooshData.metrics.config); }; // Let MetricsKit help build the array from a varargs list of sources where some args are already arrays of other sources (only works one level deep)
 * @see metrics.system.configSources.sources for simple creation of the return value of config sources.
 */
Config.prototype.sources = function sources() {};

/**
 * Search through the configuration sources provided by "metrics.system.configSources()", looking for the highest precedence value for "key"
 * If no config sources provided, look for values in the DEFAULTS constant
 * "keypath" can be a simple top-level config key such as "postFrequency" or a compound "path", such as fieldsMap.cookies
 * @param {String} keyPath the dot-separated (".") path to the desired config value.
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Promise} A Promise of the value at the reached keypath. Returns "null" if the key or key's value is not found.
 * Values found in later (farthest in array) dictionaries of key/value pairs overwrite earlier dictionaries.
 * @see metrics.system.configSources.setDelegate()
 */
Config.prototype.value = function value(keyPath, topic) {
    var getConfigValueFn = function () {
        var cachedSource = this.cachedSource();
        var serviceSource = this.serviceSource();
        var configSourcesArray = this.sources();
        var savedDebugSource = this.debugSource(); // NOTE: Always go through the accessor method, since it may need to be retrieved from localStorage
        var sourceProvided = cachedSource || serviceSource || configSourcesArray || savedDebugSource;
        var sourcesToCheck;

        // show relevant warnings
        if (!configSourcesArray && !serviceSource && !(keyPath in this._keyPathsThatSuppressWarning)) {
            if (!this._showedNoProvidedSourceWarning) {
                this._showedNoProvidedSourceWarning = true;
                this.logger.warn(
                    'Metrics config: No config provided via delegate or fetched via init(), using cached config values.'
                );
            }
        }
        if (savedDebugSource) {
            if (!this._showedDebugWarning) {
                // We do this in case developers forget to clear this and wonder why the app isn't working correctly in normal running.
                this._showedDebugWarning = true;
                this.logger.warn(
                    '"debugSource" found.\nThis will override any same-named client-supplied configSource fields.\nThis setting "sticks" across session, use "setDebugSource(null)" to clear'
                );
            }
        }

        if (!reflect.isArray(configSourcesArray)) {
            configSourcesArray = [configSourcesArray];
        }

        // disable the event only if there are no provided sources
        // In case of fetch config failed and no cached config in local
        if (keyPath === 'disabled') {
            if (sourceProvided) {
                sourcesToCheck = [cachedSource, serviceSource, configSourcesArray, savedDebugSource];
            } else {
                sourcesToCheck = [DEFAULTS];
            }
        } else {
            // For non-disabling rules, check all sources
            // Let "DEFAULTS" be overwritten by cachedSource, then serviceSource, then client-supplied configSources,
            // and then let "savedDebugSource" overwrite everyone
            sourcesToCheck = [DEFAULTS, cachedSource, serviceSource, configSourcesArray, savedDebugSource];
        }

        sourcesToCheck = this.configSourcesWithOverrides(sourcesToCheck, topic || this.topic());
        // Pass each source as an individual argument; valueForKeyPath won't expand configSourcesArray if it is nested in sourcesToCheck
        return keyValue.valueForKeyPath.apply(null, [keyPath].concat(sourcesToCheck));
    }.bind(this);

    if (this._configFetchPromise) {
        return this._configFetchPromise.then(getConfigValueFn);
    } else {
        var value = getConfigValueFn();
        return Promise.resolve(value);
    }
};

/**
 * Pushes any subsections within a config source to the front of the provided config sources array if the subsection key matches with the specified topic.
 * This method is used by the default implementation of 'value(keyPath)' to determine precedence
 * of config sources for the given topic.
 * Subsections that are later in the array will take precedence over earlier subsections.
 * Note that if one of the config sources is an array, this method will traverse one level deep
 * to check for the presence of a dictionary that may contain a desired subsection.
 * We traverse one level deep to maintain parity with _utils.keyValue.valueForKeyPath() which will be used to traverse the config sources
 * @param {Array} configSources
 * @param {String} topic
 * @returns {Array} returnSources
 */
Config.prototype.configSourcesWithOverrides = function configSourcesWithOverrides(configSources, topic) {
    var returnSources = configSources;
    if (configSources && configSources.length && topic) {
        returnSources = [];
        for (var i = 0; i < configSources.length; i++) {
            var source = configSources[i];
            if (source) {
                if (reflect.isArray(source) && source.length) {
                    var subarray = [];
                    for (var j = 0; j < source.length; j++) {
                        _appendSectionAndSubsectionToConfigSources(subarray, topic, source[j]);
                    }
                    returnSources.push(subarray);
                } else {
                    _appendSectionAndSubsectionToConfigSources(returnSources, topic, source);
                }
            }
        }
    }
    return returnSources;
};

/**
 * Set's a "priority" configSource that will override any same-named client-supplied configSource fields.
 * This can be done in code (e.g. in testcases) or, more typically, in Web Inspector when debugging or testing a running app (client) using MetricsKit.
 * This is useful when testing, both in testcases and at runtime. One example would be to set a temporary "bag" structure that could then be tweaked at will, e.g. blacklisting fields, etc.
 * This setting "sticks" across session so that it can be set, the app restarted, and the values will be present at the earliest runnings of the app.
 * Use "setDebugSource(null)" to clear this value
 * NOTE: If no "localStorage" is available (e.g. when testing), this value will only last for the session or until it is explicitly cleared.
 * Here is an example of how to use this to test an app at runtime (and/or launch time)
 *      Run the app
 *      Open Web Inspector
 *      Set a variable to bag contents, e.g. var debugBag = itms.getBag();
 *      Call: metrics.config.setDebugSource(debugBag.metrics);
 *      enter: debugBag.metrics.disabled=true;
 *      Then do some things to generate events and make sure that:
 *          The app doesn’t crash
 *          No JavaScript events are generated in the console
 *          The events aren’t sent
 *      Reset that by entering: delete debugBag.metrics.disabled
 *      enter: debugBag.metrics.blacklistedEvents = [“page”, “click”];
 *      Then do some things to generate events and make sure that:
 *          The app doesn’t crash
 *          No JavaScript events are generated in the console
 *          Those events, and only those events, aren’t sent
 *      I save the object you set via metrics.config.setDebugSource to localStorage to facilitate testing at app startup, so remember to clear it out when you’re done or you’ll be confused why things aren’t working right in the future:
 *      metrics.config.setDebugSource();
 *      If there are values you want to be in effect at app-launch, just do the tweaking to the bag before your call to metrics.config.setDebugSource(debugBag.metrics);, passing in the tweaked bag.
 * @param aDebugSource a plain old JavaScript object with keys and values which will be searched when config is requested.
 * @returns {*} debugSource
 */
Config.prototype.setDebugSource = function setDebugSource(aDebugSource) {
    this._debugSource = aDebugSource || null;
    return storage.saveObjectToStorage(this.environment.localStorageObject(), this.DEBUG_SOURCE_KEY, this._debugSource);
};

/**
 * Return any previously set debugSource which would be stored in localStorage.
 * If not present in localStorage, the class variable value of debugSource will be returned.
 * @returns {*} debugSource
 */
Config.prototype.debugSource = function debugSource() {
    if (this._debugSource) ; else {
        // Otherwise look in localStorage for one...
        this._debugSource = storage.objectFromStorage(this.environment.localStorageObject(), this.DEBUG_SOURCE_KEY);
    }
    return this._debugSource;
};

/**
 * Save a source to localStorage which will have config values that can be used in the next visit until a fresh config is fetched
 * @param {Object} aSource
 * @return {Object}
 */
Config.prototype.setCachedSource = function setCachedSource(aSource) {
    this._cachedSource = aSource || null;
    return storage.saveObjectToStorage(
        this.environment.localStorageObject(),
        this.CACHED_SOURCE_KEY,
        this._cachedSource
    );
};

/**
 * Return any previously set savedSource which would be stored in localStorage.
 * The class variable value of savedSource will be returned if non-null to avoid expensive reads from disk.
 * @return {Object}
 */
Config.prototype.cachedSource = function cachedSource() {
    if (this._cachedSource) ; else {
        // Otherwise look in localStorage for one...
        this._cachedSource = storage.objectFromStorage(this.environment.localStorageObject(), this.CACHED_SOURCE_KEY);
    }
    return this._cachedSource;
};

/**
 * Set a source, typically one that was fetched from the config endpoint,
 * which will have config values that can be overwritten by clients via config.setDelegate
 * @param {Object} aServiceSource
 * @deprecated
 * @return {Object}
 */
Config.prototype.setServiceSource = function setServiceSource(aServiceSource) {
    this._serviceSource = aServiceSource;
    return this._serviceSource;
};

/**
 * Returns a config source that was retrieved from the metrics config service endpoint
 * @deprecated
 * @return {Object}
 */
Config.prototype.serviceSource = function serviceSource() {
    return this._serviceSource;
};

/**
 * Initialize config by setting config delegate or fetching it from the config endpoint as necessary
 * If we wanted config to persist across page turns, we could save it via setCachedSource and fetch it every time we wake up,
 * but we expect most clients to be single page apps
 *
 * @param {Function} (optional) configSourcesFn - a function that returns an array of key/value objects (dictionaries) for all of the config sources
 *                                                (e.g. the bag, the page, the control parent, etc.).
 * @return {Promise} A Promise for the Config initialization. Returns an rejected Promise if failed to fetch config from server
 */
Config.prototype.init = function init(configSourcesFn) {
    var isDefaultConfig = this._topic === NO_TOPIC_KEY || !reflect.isFunction(configSourcesFn);

    if (isDefaultConfig) {
        this.logger.warn(
            'config.init(): Falling back to default config because configSourcesFn or a valid topic was not provided'
        );
    }

    // default config does not need to initialize
    if (this._initCalled || isDefaultConfig) {
        return Promise.resolve(this);
    }

    this._initCalled = true;
    var self = this;

    this._configFetchPromise = Promise.resolve(configSourcesFn())
        .then(function (configSources) {
            self.setDelegate({
                sources: function sources() {
                    return configSources;
                }
            });
            self._initialized = true;
            return self;
        })
        .catch(function (error) {
            self._initCalled = false;
            self._initialized = false;
            throw error;
        });

    return this._configFetchPromise;
};

/**
 * Release resources of the config
 */
Config.prototype.cleanup = function cleanup() {
    this._initCalled = this._initialized = false;
    this.setCachedSource();
    this.setDebugSource();
    this.resetDelegate();
    this.environment = null;
    this.network = null;
    this.logger = null;
    this._topic = null;
    this._debugSource = null;
    this._cachedSource = null;
    this._serviceSource = null;
    this._initCalled = false;
    this._initialized = false;
    this._showedDebugWarning = false;
    this._showedNoProvidedSourceWarning = false;
    this._configFetchPromise = null;
};

/**
 * Indicates whether or not config has initialized.
 * Initialization is accomplished in one of the following ways:
 *     1) a service source is set via a call to config.setServiceSource() TODO: Deprecated
 *     2) a source function delegate is set via config.setDelegate()
 * @return {Boolean}
 */
Config.prototype.initialized = function initialized() {
    return this._initialized;
};

/*
 *  src/impls/metrics_config.js
 *  mt-client-config
 *
 *  Copyright © 2020 Apple Inc. All rights reserved.
 *
 */

/**
 * Metrics config implementation for Config
 * This class is a subclass of Config to provide the business methods for metrics collection
 * @param topic
 * @constructor
 */
var MetricsConfig = function MetricsConfig(topic) {
    Config.call(this, topic);
};

MetricsConfig.prototype = Object.create(Config.prototype);
MetricsConfig.prototype.constructor = MetricsConfig;

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

/**
 * Boolean config value which, when "true", tells clients to avoid all metrics code paths (different than simply not sending metrics).
 * Useful for avoiding discovered client bugs.
 * NOTE1: This will cause unrecoverable event loss, as the clients will not be recording events at all.
 * NOTE2: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
 * if a client overrides "recordEvent", these checks will still take effect.
 * We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded.
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Promise}
 */
MetricsConfig.prototype.disabled = function disabled(topic) {
    return this.value('disabled', topic).then(function (disabled) {
        return !!disabled;
    });
};

/** @DEPERECATED per Inclusive Software Efforts; use denylistedEvents instead
 * Array config value which instructs clients to avoid sending particular event types.
 * Useful for reducing server processing in emergencies by abandoning less-critical events.
 * Useful for dealing with urgent privacy concerns, etc., around specific events.
 * NOTE1: This will cause unrecoverable event loss, as the clients will not be recording events at all.
 * NOTE2: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
 * if a client overrides "recordEvent", these checks will still take effect.
 * We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Promise} Guaranteed to always return a Promise with the valid array, though the array may be empty if the value was unset in config
 */
MetricsConfig.prototype.blacklistedEvents = function blacklistedEvents(topic) {
    return this.denylistedEvents(topic);
};

/**
 * Array config value which instructs clients to avoid sending particular event types.
 * Useful for reducing server processing in emergencies by abandoning less-critical events.
 * Useful for dealing with urgent privacy concerns, etc., around specific events.
 * NOTE1: This will cause unrecoverable event loss, as the clients will not be recording events at all.
 * NOTE2: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
 * if a client overrides "recordEvent", these checks will still take effect.
 * We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Promise} Guaranteed to always return a Promise with the valid array, though it may be empty if the value was unset in config
 */
MetricsConfig.prototype.denylistedEvents = function denylistedEvents(topic) {
    var blacklistedEventsArray = this.value('blacklistedEvents', topic)
        .then(function (returnArray) {
            return returnArray || [];
        })
        .catch(function () {
            return [];
        });
    var denylistedEventsArray = this.value('denylistedEvents', topic)
        .then(function (returnArray) {
            return returnArray || [];
        })
        .catch(function () {
            return [];
        });
    return Promise.all([blacklistedEventsArray, denylistedEventsArray]).then(function (outputs) {
        var blacklistedEventsArray = outputs[0];
        var denylistedEventsArray = outputs[1];
        return dedupedArray(blacklistedEventsArray, denylistedEventsArray);
    });
};

/**
 * Returns a deduped array (similar to a Set object) using the contents from both arrayA and arrayB
 * @param {Array} arrayA the first array to dedupe
 * @param {Array} arrayB the other array to dedupe
 * @return {Array} The deduped array
 */
function dedupedArray(arrayA, arrayB) {
    var tempDict = {}; // necessary for returning array of unique values and not having access to Set object in ES5
    var returnArray = [];
    if (arrayA) {
        for (var i = 0; i < arrayA.length; i++) {
            tempDict[arrayA[i]] = 0; // value for key doesn't matter; we want a list of unique values
        }
    }
    if (arrayB) {
        for (var j = 0; j < arrayB.length; j++) {
            tempDict[arrayB[j]] = 0; // value for key doesn't matter; we want a list of unique values
        }
    }
    returnArray = Object.keys(tempDict);
    return returnArray;
}

/**
 * Array config value which instructs clients to avoid sending particular event fields.
 * Useful for dealing with urgent privacy concerns, etc., around specific event fields (e.g. dsid)
 * NOTE: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
 * if a client overrides "recordEvent", these checks will still take effect.
 * We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Promise} Guaranteed to always return a Promise with the valid array, though it may be empty if the value was unset in config
 */
MetricsConfig.prototype.blacklistedFields = function blacklistedFields(topic) {
    return this.denylistedFields(topic);
};

/**
 * Array config value which instructs clients to avoid sending particular event fields.
 * Useful for dealing with urgent privacy concerns, etc., around specific event fields (e.g. dsid)
 * NOTE: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
 * if a client overrides "recordEvent", these checks will still take effect.
 * We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Promise} Guaranteed to always return a Promise valid array, though it may be empty if the value was unset in config
 */
MetricsConfig.prototype.denylistedFields = function denylistedFields(topic) {
    var blacklistedFieldsArray = this.value('blacklistedFields', topic)
        .then(function (returnArray) {
            return returnArray || [];
        })
        .catch(function () {
            return [];
        });
    var denylistedFieldsArray = this.value('denylistedFields', topic)
        .then(function (returnArray) {
            return returnArray || [];
        })
        .catch(function () {
            return [];
        });
    return Promise.all([blacklistedFieldsArray, denylistedFieldsArray]).then(function (outputs) {
        var blacklistedFieldsArray = outputs[0];
        var denylistedFieldsArray = outputs[1];
        return dedupedArray(blacklistedFieldsArray, denylistedFieldsArray);
    });
};

/** @DEPRECATED per Inclusive Software Efforts; use removeDenylistedFields instead
 * Remove all blacklisted fields from the passed-in object.
 * IMPORTANT: This action is performed in-place for performance of not having to create new objects each time.
 * NOTE: Typically all event_handlers will call this in addition to "recordEvent()" calling it because that way
 * if a client overrides "recordEvent", these checks will still take effect.
 * We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
 * @param {Object} eventFields a dictionary of event data
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Promise} the passed-in object with any blacklisted fields removed
 */
MetricsConfig.prototype.removeBlacklistedFields = function removeBlacklistedFields(eventFields, topic) {
    return this.removeDenylistedFields(eventFields, topic);
};

/**
 * Remove all denylisted fields from the passed-in object.
 * IMPORTANT: This action is performed in-place for performance of not having to create new objects each time.
 * NOTE: Typically all event_handlers will call this in addition to "recordEvent()" calling it because that way
 * if a client overrides "recordEvent", these checks will still take effect.
 * We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
 * @param {Object} eventFields a dictionary of event data
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Promise} the passed-in object with any denylisted fields removed
 */
MetricsConfig.prototype.removeDenylistedFields = function removeDenylistedFields(eventFields, topic) {
    if (eventFields) {
        return this.denylistedFields(topic).then(function (denylistedFieldsArray) {
            for (var ii = 0; ii < denylistedFieldsArray.length; ii++) {
                var aDenylistedField = denylistedFieldsArray[ii];
                // Double check this is not null (or empty string), or "delete" will blow up...
                if (aDenylistedField) {
                    if (aDenylistedField in eventFields) {
                        delete eventFields[aDenylistedField];
                    }
                }
            }
            return eventFields;
        });
    } else {
        return Promise.resolve(eventFields);
    }
};

/** @DEPRECATED per Inclusive Software Efforts; use metricsDisabledOrDenylistedEvent instead
 * Convenience function used by event handlers to determine if they should build and return metricsData.
 * NOTE: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
 * if a client overrides "recordEvent", these checks will still take effect.
 * We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
 * @param {String} anEventType
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Promise} returns "true" if <b>either</b> "disabled()" is true or "blacklistedEvents()" contains this eventType
 */
MetricsConfig.prototype.metricsDisabledOrBlacklistedEvent = function metricsDisabledOrBlacklistedEvent(
    anEventType,
    topic
) {
    return this.metricsDisabledOrDenylistedEvent(anEventType, topic);
};

/**
 * Convenience function used by event handlers to determine if they should build and return metricsData.
 * NOTE: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
 * if a client overrides "recordEvent", these checks will still take effect.
 * We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
 * @param {String} anEventType
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Boolean} returns "true" if <b>either</b> "disabled()" is true or "denylistedEvents()" contains this eventType
 */
MetricsConfig.prototype.metricsDisabledOrDenylistedEvent = function metricsDisabledOrDenylistedEvent(
    anEventType,
    topic
) {
    return this.disabled(topic).then(
        function (disabled) {
            return (
                disabled ||
                (anEventType
                    ? this.denylistedEvents(topic).then(function (denylistedEvents) {
                          return denylistedEvents.indexOf(anEventType) > -1;
                      })
                    : false)
            );
        }.bind(this)
    );
};

/**
 * Config map which instructs clients to de-res (lower the resolution of) particular event fields.
 * The Privacy team typically requires device capacity information to be de-resed.
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Promise} An array of config objects { fieldName, (optional) magnitude, (optional) significantDigits }
 * Guaranteed to always return a valid array, though it may be empty if the value was unset in config
 */
MetricsConfig.prototype.deResFields = function deResFields(topic) {
    return this.value('deResFields', topic).then(function (returnArray) {
        return returnArray || [];
    });
};

/**
 * De-res appropriate fields in the passed-in object by lowering the resolution of those field values.
 * For example, a raw number of bytes "de-res"'d to MB, but without the "floor" filter, would look like these examples:
 *      31708938240/1024/1024 ==> 30240
 *      15854469120/1024/1024 ==> 15120
 *      63417876480/1024/1024 ==> 60480
 *
 * With the "floor" formula we replace the two least significant digits with "00"
 * Doing so will convert values like so:
 *
 *      31708938240/1024/1024 ==> 30200
 *      15854469120/1024/1024 ==> 15100
 *      63417876480/1024/1024 ==> 60400
 *
 * IMPORTANT: This action is performed in-place for performance of not having to create new objects each time.
 * NOTE: Be careful not to call this method more than once for a given event, as de-resing a number more than
 * once can lead to inaccurate reporting (numbers will likely be smaller than their real values)
 * @param {Object} eventFields a dictionary of event data
 * @param {String} (optional) topic an 'override' topic which will override the main topic.
 * @returns {Promise} the passed-in object with any fields de-resed
 */
MetricsConfig.prototype.applyDeRes = function applyDeRes(eventFields, topic) {
    if (eventFields) {
        return this.deResFields(topic).then(function (deResFieldsConfigArray) {
            var fieldName;

            deResFieldsConfigArray.forEach(function (deResFieldConfig) {
                fieldName = deResFieldConfig.fieldName;
                if (fieldName in eventFields) {
                    eventFields[fieldName] = number.deResNumber(
                        eventFields[fieldName],
                        deResFieldConfig.magnitude,
                        deResFieldConfig.significantDigits
                    );
                }
            });

            return eventFields;
        });
    } else {
        return Promise.resolve(eventFields);
    }
};

export default Config;
export { MetricsConfig };
