import { useCallback, useState, type FC, type ReactNode } from "react";
import { DbContext } from ".";
import type { IDBPDatabase } from "idb";

interface IDBProvider {
  children: ReactNode;
}

export const DbProvider: FC<IDBProvider> = ({ children }) => {
  const [db, _setDb] = useState<IDBPDatabase | null>(null);

  const setDb = useCallback((db: IDBPDatabase) => _setDb(db), []);

  return (
    <DbContext.Provider
      value={{
        db,
        connected: Boolean(db),
        setDb,
      }}
    >
      {children}
    </DbContext.Provider>
  );
};
