import React, { createContext, useContext, useMemo, useCallback } from "react";
import defaultNetworkApi from "./api";
import { fromPromise } from "xstate";
import { useMachine } from "@xstate/react";
import { serviceStatusMachine } from "./machine";
const ServiceStatusContext = createContext({
    incidents: [],
    isLoading: false,
    lastUpdateTime: undefined,
    error: undefined,
    updateData: () => Promise.resolve(),
    context: { tickers: [] },
});
export function useServiceStatus() {
    return useContext(ServiceStatusContext);
}
function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()[\]\\]/g, "\\$&"); // $& means the whole matched string
}
export 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)));
}
// filter out service status incidents by given currencies or fallback on context currencies
export function useFilteredServiceStatus(filters) {
    const stateData = useContext(ServiceStatusContext);
    const { incidents, context } = stateData;
    const filteredIncidents = useMemo(() => {
        return filterServiceStatusIncidents(incidents, filters?.tickers || context?.tickers);
    }, [incidents, context, filters?.tickers]);
    return { ...stateData, incidents: filteredIncidents };
}
export const ServiceStatusProvider = ({ children, autoUpdateDelay, networkApi = defaultNetworkApi, context, }) => {
    const fetchData = useCallback(async () => {
        const serviceStatusSummary = await networkApi.fetchStatusSummary();
        return {
            incidents: serviceStatusSummary.incidents,
            updateTime: Date.now(),
        };
    }, [networkApi]);
    const [state, send] = useMachine(serviceStatusMachine.provide({
        actors: {
            fetchData: fromPromise(fetchData),
        },
        delays: {
            AUTO_UPDATE_DELAY: autoUpdateDelay,
        },
    }));
    const api = useMemo(() => ({
        updateData: async () => {
            send({
                type: "UPDATE_DATA",
            });
        },
    }), [send]);
    const value = { ...(state.context || {}), ...api, context };
    return React.createElement(ServiceStatusContext.Provider, { value: value }, children);
};
//# sourceMappingURL=index.js.map