import { useQuery } from "@tanstack/react-query";
import { useLocation } from "react-router-dom";
import { useTranslation } from "react-i18next";

import { wwwAXIOS } from "src/Www";
import { GetSitesAPI } from "src/wwwAPI";
import { useSiteStore } from "src/Stores";
import { getSiteName } from "src/Utility";

export default function useGetSites() {
  const { isSiteWindowOpened } = useSiteStore();

  const { t } = useTranslation();

  const { pathname } = useLocation();

  return useQuery({
    enabled: isSiteWindowOpened && pathname.startsWith("/qwilight/site"),
    queryKey: ["sites"],
    queryFn: async () => {
      const { data } = await wwwAXIOS.get<GetSitesAPI>("/sites");
      return data.map(
        ({ siteID, siteName, siteConfigure, hasCipher, avatarCount }) => ({
          siteID,
          siteName: getSiteName(siteName, t),
          siteConfigure,
          hasCipher,
          avatarCount,
        }),
      );
    },
    initialData: [],
  });
}
