"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceStatusProvider = exports.useFilteredServiceStatus = exports.filterServiceStatusIncidents = exports.useServiceStatus = void 0;
const react_1 = __importStar(require("react"));
const api_1 = __importDefault(require("./api"));
const xstate_1 = require("xstate");
const react_2 = require("@xstate/react");
const machine_1 = require("./machine");
const ServiceStatusContext = (0, react_1.createContext)({
    incidents: [],
    isLoading: false,
    lastUpdateTime: undefined,
    error: undefined,
    updateData: () => Promise.resolve(),
    context: { tickers: [] },
});
function useServiceStatus() {
    return (0, react_1.useContext)(ServiceStatusContext);
}
exports.useServiceStatus = useServiceStatus;
function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()[\]\\]/g, "\\$&"); // $& means the whole matched string
}
function filterServiceStatusIncidents(incidents, tickers = []) {
    if (!tickers || tickers.length === 0 || !incidents || incidents.length === 0) {
        return [];
    }
    const tickersRegex = new RegExp(escapeRegExp(tickers.join("|")), "i");
    return incidents.filter(({ components }) => !components || // dont filter out if no components
        components.length === 0 ||
        components.some(({ name }) => tickersRegex.test(name)));
}
exports.filterServiceStatusIncidents = filterServiceStatusIncidents;
// filter out service status incidents by given currencies or fallback on context currencies
function useFilteredServiceStatus(filters) {
    const stateData = (0, react_1.useContext)(ServiceStatusContext);
    const { incidents, context } = stateData;
    const filteredIncidents = (0, react_1.useMemo)(() => {
        return filterServiceStatusIncidents(incidents, filters?.tickers || context?.tickers);
    }, [incidents, context, filters?.tickers]);
    return { ...stateData, incidents: filteredIncidents };
}
exports.useFilteredServiceStatus = useFilteredServiceStatus;
const ServiceStatusProvider = ({ children, autoUpdateDelay, networkApi = api_1.default, context, }) => {
    const fetchData = (0, react_1.useCallback)(async () => {
        const serviceStatusSummary = await networkApi.fetchStatusSummary();
        return {
            incidents: serviceStatusSummary.incidents,
            updateTime: Date.now(),
        };
    }, [networkApi]);
    const [state, send] = (0, react_2.useMachine)(machine_1.serviceStatusMachine.provide({
        actors: {
            fetchData: (0, xstate_1.fromPromise)(fetchData),
        },
        delays: {
            AUTO_UPDATE_DELAY: autoUpdateDelay,
        },
    }));
    const api = (0, react_1.useMemo)(() => ({
        updateData: async () => {
            send({
                type: "UPDATE_DATA",
            });
        },
    }), [send]);
    const value = { ...(state.context || {}), ...api, context };
    return react_1.default.createElement(ServiceStatusContext.Provider, { value: value }, children);
};
exports.ServiceStatusProvider = ServiceStatusProvider;
//# sourceMappingURL=index.js.map