import {DBSchema, openDB} from 'idb';
import {useCallback, useEffect, useState} from 'react';
import {useLocation} from 'react-router-dom';

type FilterDB = {
  filterGroup: {
    keyPath: string;
    value: {
      path: string;
      auths: string;
    };
  };
} & DBSchema;

function openFilterDB() {
  return openDB<FilterDB>('filterGroup', 1, {
    upgrade(db) {
      if (!db.objectStoreNames.contains('filterGroup')) {
        db.createObjectStore('filterGroup', {keyPath: 'path'});
      }
    },
  });
}

export function useFilterDB() {
  const [state, setState] = useState('');
  const {pathname} = useLocation();

  const update = useCallback(
    async function () {
      const db = await openFilterDB();
      const data = await db.get('filterGroup', IDBKeyRange.only(pathname));
      db.close();
      data && setState(data.auths);
    },
    [pathname],
  );

  const set = useCallback(
    async function (auths: string) {
      const db = await openFilterDB();
      await db.put('filterGroup', {path: pathname, auths});
      db.close();
      setState(auths);
    },
    [pathname],
  );

  useEffect(
    function () {
      update();
    },
    [update],
  );

  return [state, {update, set}] as const;
}
