/* *
 *
 *  (c) 2009-2026 Highsoft AS
 *
 *  A commercial license may be required depending on use.
 *  See www.highcharts.com/license
 *
 *
 *  Authors:
 *  - Sophie Bremer
 *
 * */
'use strict';
import DataConnector from './Connectors/DataConnector.js';
import U from '../Core/Utilities.js';
var addEvent = U.addEvent, fireEvent = U.fireEvent, merge = U.merge;
/* *
 *
 *  Class
 *
 * */
/**
 * Data pool to load connectors on-demand.
 *
 * @class
 * @name Data.DataPool
 *
 * @param {DataPoolOptions} options
 * Pool options with all connectors.
 */
var DataPool = /** @class */ (function () {
    /* *
     *
     *  Constructor
     *
     * */
    function DataPool(options) {
        this.options = merge(DataPool.defaultOptions, options);
        this.connectors = {};
        this.waiting = {};
    }
    /* *
     *
     *  Methods
     *
     * */
    /**
     * Emits an event on this data pool to all registered callbacks of the given
     * event.
     *
     * @param {DataTable.Event} e
     * Event object with event information.
     */
    DataPool.prototype.emit = function (e) {
        fireEvent(this, e.type, e);
    };
    /**
     * Loads the connector.
     *
     * @function Data.DataPool#getConnector
     *
     * @param {string} connectorId
     * ID of the connector.
     *
     * @return {Promise<Data.DataConnectorType>}
     * Returns the connector.
     */
    DataPool.prototype.getConnector = function (connectorId) {
        var _this = this;
        var connector = this.connectors[connectorId];
        // Already loaded
        if (connector === null || connector === void 0 ? void 0 : connector.loaded) {
            return Promise.resolve(connector);
        }
        var waitingList = this.waiting[connectorId];
        // Start loading
        if (!waitingList) {
            waitingList = this.waiting[connectorId] = [];
            var connectorOptions = this.getConnectorOptions(connectorId);
            if (!connectorOptions) {
                throw new Error("Connector '".concat(connectorId, "' not found."));
            }
            // eslint-disable-next-line @typescript-eslint/no-floating-promises
            this
                .loadConnector(connectorOptions)
                .then(function (connector) {
                delete _this.waiting[connectorId];
                for (var i = 0, iEnd = waitingList.length; i < iEnd; ++i) {
                    waitingList[i][0](connector);
                }
            })['catch'](function (error) {
                delete _this.waiting[connectorId];
                for (var i = 0, iEnd = waitingList.length; i < iEnd; ++i) {
                    waitingList[i][1](error);
                }
            });
        }
        // Add request to waiting list
        return new Promise(function (resolve, reject) {
            waitingList.push([resolve, reject]);
        });
    };
    /**
     * Returns the IDs of all connectors.
     *
     * @private
     *
     * @return {Array<string>}
     * Names of all connectors.
     */
    DataPool.prototype.getConnectorIds = function () {
        var connectors = this.options.connectors, connectorIds = [];
        for (var i = 0, iEnd = connectors.length; i < iEnd; ++i) {
            connectorIds.push(connectors[i].id);
        }
        return connectorIds;
    };
    /**
     * Loads the options of the connector.
     *
     * @private
     *
     * @param {string} connectorId
     * ID of the connector.
     *
     * @return {DataConnectorTypeOptions | undefined}
     * Returns the options of the connector, or `undefined` if not found.
     */
    DataPool.prototype.getConnectorOptions = function (connectorId) {
        var connectors = this.options.connectors;
        for (var i = 0, iEnd = connectors.length; i < iEnd; ++i) {
            if (connectors[i].id === connectorId) {
                return connectors[i];
            }
        }
    };
    /**
     * Tests whether the connector has never been requested.
     *
     * @param {string} connectorId
     * Name of the connector.
     *
     * @return {boolean}
     * Returns `true`, if the connector has never been requested, otherwise
     * `false`.
     */
    DataPool.prototype.isNewConnector = function (connectorId) {
        return !this.connectors[connectorId];
    };
    /**
     * Instantiates the connector class for the given options and loads its
     * data.
     *
     * @private
     *
     * @param {Data.DataPoolConnectorOptions} options
     * Options of connector.
     *
     * @return {Promise<Data.DataConnectorType>}
     * Returns the connector.
     */
    DataPool.prototype.loadConnector = function (options) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this.emit({
                type: 'load',
                options: options
            });
            var ConnectorClass = DataConnector.types[options.type];
            if (!ConnectorClass) {
                throw new Error("Connector type not found. (".concat(options.type, ")"));
            }
            var connector = _this.connectors[options.id] =
                new ConnectorClass(options);
            // eslint-disable-next-line @typescript-eslint/no-floating-promises
            connector
                .load()
                .then(function (_a) {
                var converter = _a.converter;
                connector.converter = converter;
                connector.loaded = true;
                _this.emit({
                    type: 'afterLoad',
                    options: options
                });
                resolve(connector);
            })['catch'](reject);
        });
    };
    /**
     * Cancels all data connectors pending requests.
     */
    DataPool.prototype.cancelPendingRequests = function () {
        var connectors = this.connectors;
        for (var _i = 0, _a = Object.keys(connectors); _i < _a.length; _i++) {
            var connectorKey = _a[_i];
            connectors[connectorKey].stopPolling();
        }
    };
    /**
     * Registers a callback for a specific event.
     *
     * @function Highcharts.DataPool#on
     *
     * @param {string} type
     * Event type as a string.
     *
     * @param {Highcharts.EventCallbackFunction<Highcharts.DataPool>} callback
     * Function to register for an event callback.
     *
     * @return {Function}
     * Function to unregister callback from the event.
     */
    DataPool.prototype.on = function (type, callback) {
        return addEvent(this, type, callback);
    };
    /**
     * Sets connector options under the specified `options.id`.
     *
     * @param options
     * Connector options to set.
     */
    DataPool.prototype.setConnectorOptions = function (options) {
        var connectorsOptions = this.options.connectors;
        var connectorsInstances = this.connectors;
        this.emit({
            type: 'setConnectorOptions',
            options: options
        });
        for (var i = 0, iEnd = connectorsOptions.length; i < iEnd; ++i) {
            if (connectorsOptions[i].id === options.id) {
                connectorsOptions.splice(i, 1);
                break;
            }
        }
        // TODO: Check if can be refactored
        if (connectorsInstances[options.id]) {
            connectorsInstances[options.id].stopPolling();
            delete connectorsInstances[options.id];
        }
        connectorsOptions.push(options);
        this.emit({
            type: 'afterSetConnectorOptions',
            options: options
        });
    };
    /* *
     *
     *  Static Properties
     *
     * */
    DataPool.defaultOptions = {
        connectors: []
    };
    return DataPool;
}());
/* *
 *
 *  Default Export
 *
 * */
export default DataPool;
