import { useCallback, useEffect, useState } from "react";
import iso from "iso-3166-1";
import Fuse from "fuse.js";
import { getGenerators } from "../domain/apiMethods";

const useCountryLookup = genMethod => {
  const [state, setState] = useState(null);

  useEffect(() => {
    const lookup = async () => {
      const { generators } = await getGenerators();
      const countryLookup = Object.fromEntries(
        generators.map(({ generationMethod, countryLocks }) => [
          generationMethod,
          new Fuse(
            countryLocks
              .map(c => iso.whereAlpha2(c))
              .filter(c => c !== null && c !== undefined),
            {
              keys: ["country"],
            }
          ),
        ])
      );
      setState(countryLookup);
    };
    lookup();
  }, []);

  const callback = useCallback(
    search => state?.[genMethod]?.search(search, { limit: 5 }),
    [state, genMethod]
  );

  if (state === null) {
    return null;
  }

  return callback;
};

export default useCountryLookup;
