import { useEffect, useRef } from 'react';
// *** Model 层数据引用相关 ***
import {
  docSpeakerHooks,
  documentHooks,
  iDocIDType,
} from '../../../../../documentModel';

const useSpeakerSplitFinish = (callback: () => void) => {
  const { documentData } = documentHooks.useDocumentData();
  const { docId } = documentData || {};
  const { docSpeakerData } = docSpeakerHooks.useDocSpeakerData();
  const cacheSpeakersSplitIsLoading = useRef<boolean>(false);
  const cacheDocId = useRef<iDocIDType | undefined>();
  const { speakersSplitIsOpen, speakersSplitIsLoading } = docSpeakerData || {};
  useEffect(() => {
    speakersSplitIsLoading && (cacheSpeakersSplitIsLoading.current = true);
    cacheDocId.current = docId;
  }, [docId, speakersSplitIsLoading]);

  useEffect(() => {
    if (cacheDocId.current !== docId) {
      cacheSpeakersSplitIsLoading.current = false;
    }
    return () => {
      cacheDocId.current = undefined;
      cacheSpeakersSplitIsLoading.current = false;
    };
  }, [docId]);

  useEffect(() => {
    if (
      cacheDocId.current &&
      cacheDocId.current === docId &&
      cacheSpeakersSplitIsLoading.current === true &&
      !speakersSplitIsLoading &&
      speakersSplitIsOpen
    ) {
      typeof callback === 'function' && callback();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [docId, speakersSplitIsLoading, speakersSplitIsOpen]);
};

export { useSpeakerSplitFinish };
