import { useCallback, useEffect, useState } from "react";

/**
 * 挂载
 */
export const useMount = (func: () => void) => {
  useEffect(() => {
    func();
  }, []);
};

/**
 * 卸载
 */
export const useUnmount = (func: () => void) => {
  useEffect(
    () => () => {
      func();
    },
    []
  );
};

/**
 * forceUpdate
 */
export const useUpdate = () => {
  const [, setState] = useState({});
  return useCallback(() => setState({}), []);
};

/**
 * 动态插入script
 */
export const useScript = (urls: string[], func: Function) => {
  useEffect(() => {
    const promises = urls.map((url) => {
      const script = document.createElement("script");
      return new Promise((resolve) => {
        script.setAttribute("script-type", "hook");
        script.src = url;
        script.async = true;
        document.body.appendChild(script);
        script.onload = () => resolve(true);
      });
    });
    Promise.all(promises).then(() => func());
    return () => {
      document
        .querySelectorAll(`[script-type='hook']`)
        .forEach((script) => document.body.removeChild(script));
    };
  }, []);
};

/**
 * 动态插入link css
 */
export const useLink = (urls: string[]) => {
  useEffect(() => {
    urls.forEach((url) => {
      const link = document.createElement("link");
      link.href = url;
      link.rel = "stylesheet";
      link.setAttribute("link-type", "hook");
      document.head.appendChild(link);
    });
    return () => {
      document
        .querySelectorAll(`[link-type='hook']`)
        .forEach((link) => document.head.removeChild(link));
    };
  }, [urls]);
};
