import { useCallback, useEffect, useState } from "react";
import { openDB, IndexNames, StoreNames, StoreValue } from "idb";
import { NovelDb } from "libs/db/getDb";
import { getList } from "libs/db/history";

export default function useDbList<
  N extends StoreNames<NovelDb>,
  R extends [any, any, boolean?, boolean?]
>(
  storeName: N,
  index?: IndexNames<NovelDb, N>,
  direction: IDBCursorDirection = "next",
  rage?: R
) {
  const [isLoading, setIsLoading] = useState(false);
  const [
    { list = [], ...pages } = { page: 0, pageSize: 0, total: 0 } as PageList<
      NovelDb[N]["value"]
    >,
    setData,
  ] = useState<PageList<NovelDb[N]["value"]>>();

  const handleGetList = useCallback(
    (page: number) => {
      if (isLoading) return;
      setIsLoading(true);
      getList(storeName, index, page, 20, direction, rage).then((data) => {
        setData(data);
        setIsLoading(false);
      });
    },
    [storeName, direction, index, isLoading, rage]
  );

  useEffect(() => {
    if (!isLoading && pages.pageSize === 0) {
      handleGetList(0);
    }
  }, [handleGetList, isLoading, pages.pageSize]);

  return [list, pages, handleGetList, isLoading] as [
    typeof list,
    typeof pages,
    typeof handleGetList,
    typeof isLoading
  ];
}

export const useHistoryList = () =>
  useDbList("history", "historyIsReading", "prev", [
    [1, 0],
    [1, new Date()],
  ]);

export const useFavoriteList = () =>
  useDbList("history", "historyIsFavorite", "prev", [1, 1]);
