import { jsx as _jsx } from "react/jsx-runtime";
import Firebase from "firebase";
import React from "react";
import { useNotifications } from "../notifications";
const Context = React.createContext({
    createRecord: undefined,
    getRecords: undefined,
    firebaseDB: undefined,
});
Context.displayName = "FirebaseContext";
export const useFirebase = () => React.useContext(Context);
export const FirebaseProvider = ({ config, children, }) => {
    const { sendError } = useNotifications();
    const [db, setDb] = React.useState(null);
    React.useEffect(() => {
        Firebase.initializeApp(config);
        const db = Firebase.firestore();
        db.settings({
            timestampsInSnapshots: true,
        });
        setDb(db);
    }, []);
    const handleAsync = React.useCallback(async (action) => {
        try {
            const result = await action();
            return result;
        }
        catch (err) {
            if (err instanceof Error) {
                console.error(err);
                sendError({
                    content: err.message,
                });
            }
        }
    }, []);
    const createRecord = React.useCallback(async (collection, data) => {
        if (db) {
            const result = await handleAsync(async () => {
                const reference = await db.collection(collection).add(data);
                return reference;
            });
            return result;
        }
    }, [db, handleAsync]);
    const getRecords = React.useCallback(async (collection) => {
        if (db) {
            const result = await handleAsync(async () => {
                const reference = await db.collection(collection).get();
                return reference;
            });
            return result;
        }
    }, [db, handleAsync]);
    return (_jsx(Context.Provider, { value: {
            createRecord,
            getRecords,
            firebaseDB: db,
        }, children: children }));
};
//# sourceMappingURL=context.js.map