"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.AnnouncementProvider = exports.useAnnouncements = void 0;
const react_1 = __importStar(require("react"));
const differenceBy_1 = __importDefault(require("lodash/differenceBy"));
const xstate_1 = require("xstate");
const react_2 = require("@xstate/react");
const logic_1 = require("./logic");
const api_1 = __importDefault(require("./api"));
const machine_1 = require("./machine");
const AnnouncementsContext = (0, react_1.createContext)({
    seenIds: [],
    allIds: [],
    cache: {},
    isLoading: false,
    lastUpdateTime: undefined,
    error: undefined,
    updateCache: () => Promise.resolve(),
    setAsSeen: () => { },
});
function useAnnouncements() {
    return (0, react_1.useContext)(AnnouncementsContext);
}
exports.useAnnouncements = useAnnouncements;
const AnnouncementProvider = ({ children, context, handleLoad, handleSave, autoUpdateDelay, onNewAnnouncement, onAnnouncementRead, fetchApi = api_1.default, }) => {
    const fetchData = (0, react_1.useCallback)(async (arg0) => {
        const { allIds, cache } = arg0.input;
        const rawAnnouncements = await fetchApi.fetchAnnouncements();
        const localizedAnnouncements = (0, logic_1.localizeAnnouncements)(rawAnnouncements, context);
        const announcements = (0, logic_1.filterAnnouncements)(localizedAnnouncements, context);
        const oldAnnouncements = allIds.map((uuid) => cache[uuid]);
        const newAnnouncements = (0, differenceBy_1.default)(announcements, oldAnnouncements, announcement => announcement.uuid);
        if (onNewAnnouncement) {
            newAnnouncements.forEach(announcement => {
                onNewAnnouncement(announcement);
            });
        }
        return {
            announcements,
            updateTime: Date.now(),
        };
    }, [context, onNewAnnouncement, fetchApi]);
    const emitNewAnnouncement = (0, react_1.useCallback)(({ context }) => {
        if (onAnnouncementRead) {
            onAnnouncementRead(context.cache[context.seenId]);
        }
    }, [onAnnouncementRead]);
    const loadData = (0, react_1.useCallback)(async () => {
        const { announcements, lastUpdateTime, seenIds } = await handleLoad();
        return {
            announcements,
            lastUpdateTime,
            seenIds,
        };
    }, [handleLoad]);
    const saveData = (0, react_1.useCallback)(({ context }) => {
        const { cache, lastUpdateTime, seenIds, allIds } = context;
        const announcements = allIds.map((id) => cache[id]);
        handleSave({
            announcements,
            seenIds,
            lastUpdateTime,
        });
    }, [handleSave]);
    const [state, send] = (0, react_2.useMachine)(machine_1.announcementMachine.provide({
        actions: {
            saveData,
            emitNewAnnouncement,
        },
        actors: {
            loadData: (0, xstate_1.fromPromise)(loadData),
            fetchData: (0, xstate_1.fromPromise)(fetchData),
        },
        delays: {
            AUTO_UPDATE_DELAY: autoUpdateDelay,
        },
    }));
    const api = (0, react_1.useMemo)(() => ({
        updateCache: async () => {
            send({
                type: "UPDATE_DATA",
            });
        },
        setAsSeen: (seenId) => {
            send({
                type: "SET_AS_SEEN",
                seenId,
            });
        },
    }), [send]);
    const value = { ...state.context, ...api };
    return (react_1.default.createElement(AnnouncementsContext.Provider, { value: value }, children));
};
exports.AnnouncementProvider = AnnouncementProvider;
//# sourceMappingURL=index.js.map