import { useCallback, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { iDocumentState } from '../document.type';
import { splitedSpeakerAvatarList } from './docSpeaker.config';

// DocSpeaker Hooks
const useDocSpeakerData = () => {
  // redux 取数
  const { docId, docSpeakerDataMap } = useSelector(
    (state: { documentModel: iDocumentState }) => ({
      docScene: state.documentModel.docScene!,
      docId: state.documentModel.docId!,
      docSpeakerDataMap: state.documentModel.docSpeakerDataMap,
    }),
  );

  /** 当前文档发然人相关数据 */
  const docSpeakerData = useMemo(() => {
    if (!docId) return;
    return docSpeakerDataMap[docId];
  }, [docId, docSpeakerDataMap]);

  // 获取发言人数据
  const getSpeakerDataFromUid = useCallback(
    (ui: string) => {
      if (!docSpeakerData) return;
      return docSpeakerData.speakersData.find(
        (speakerData) => speakerData.uid === ui,
      );
    },
    [docSpeakerData, docSpeakerData?.speakersData],
  );

  // 获取未知发言人头像链接
  const getUnknownSpeakerAvatarUrl = useCallback(
    (uid: string) => {
      if (!docSpeakerData) return;
      const speakerData = docSpeakerData.speakersData.find(
        (speakerDataItem) => speakerDataItem.uid === uid,
      );
      if (speakerData) {
        return speakerData.speakerAvatar;
      }

      // 未知头像
      const avatarUrlLength = splitedSpeakerAvatarList.length;
      const uidIndex = Number.parseInt(uid, 10) % avatarUrlLength;

      return splitedSpeakerAvatarList[uidIndex];
    },
    [docSpeakerData],
  );

  return {
    // data
    docSpeakerData,
    // data function
    getSpeakerDataFromUid,
    getUnknownSpeakerAvatarUrl,
  };
};

export { useDocSpeakerData };
