import { StoreNames } from "idb";
import { NovelDb } from "libs/db/getDb";
import { delItem, getItem, putItem } from "libs/db/history";
import { useCallback, useEffect, useState } from "react";

export default function useDbItem<N extends StoreNames<NovelDb>>(
  name: N,
  defaultKey?: string
) {
  const [key, setKey] = useState(defaultKey);
  const [value, setValue] = useState<NovelDb[N]["value"]>();

  const updateValue = useCallback(() => {
    if (!key) {
      setValue(void 0);
      return;
    }
    getItem(name, key).then((value) => {
      setValue(value);
    });
  }, [name, key]);

  const put = useCallback(
    (data: NovelDb[N]["value"]) =>
      putItem(name, data)
        .then(() => setValue(data))
        .catch((e) => {}),
    [name]
  );

  const del = useCallback(
    (key: NovelDb[N]["key"]) =>
      delItem(name, key)
        .then(() => setValue(void 0))
        .catch((e) => {}),
    [name]
  );

  useEffect(() => {
    updateValue();
  }, [updateValue]);

  return [value, put, del, setKey] as [
    typeof value,
    typeof put,
    typeof del,
    typeof setKey
  ];
}

export const useHistory = (key?: string) => useDbItem("history", key);
