import { DependencyList, useEffect, useState, useMemo } from 'react';
// @ts-ignore
import { useEventEmitter, usePrevious } from 'ahooks';
// @ts-ignore
import sha1 from 'sha1';
// @ts-ignore
import differenceBy from 'lodash/differenceBy';


export function useRequest(
  factory,
  options
) {
  const { deps = [], initial, ready = true } = options || {};
  const [val, setVal] = useState(initial);
  useEffect(() => {
    if (!ready) return;
    let cancel = false;
    const promise = factory();
    if (promise === undefined || promise === null) return;
    promise
      .then((val) => {
        if (!cancel) {
          setVal(val);
        }
      })
      .catch((err) => {
        console.error(err);
      });
    return () => {
      cancel = true;
    };
  }, [...deps, ready]);

  return val;
}

export function useFileReadMarkChange$(
  diffs,
  readMarks
) {
  const fileReadMarkChange$ = useEventEmitter();
  const filePathShaMap = useMemo(() => {
    const map = new Map();
    for (const diff of diffs) {
      map.set(sha1(diff.newPath), diff.newPath);
    }
    return map;
  }, [diffs]);

  const prevReadMarks = usePrevious(readMarks);
  useEffect(() => {
    const changesA = differenceBy(
      prevReadMarks,
      readMarks,
      (readMark) => readMark.filePathSha
    );
    const changesB = differenceBy(
      readMarks,
      prevReadMarks,
      (readMark) => readMark.filePathSha
    );
    for (const change of [...changesA, ...changesB]) {
      const filePath = filePathShaMap.get(change.filePathSha);
      if (filePath) {
        fileReadMarkChange$.emit(filePath);
      }
    }
  }, [readMarks, filePathShaMap]);

  return fileReadMarkChange$;
}
