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

import { iDocumentState } from '../document.type';
import { iDocPlayerData } from './docPlayer.types';

import { docPlayerActions } from './docPlayer.operator';

// DocPlayer Hooks
export const useDocPlayerData = () => {
  const dispatch = useDispatch();
  // redux 取数
  const { docId, docScene, docPlayerDataMap } = useSelector(
    (state: { documentModel: iDocumentState }) => ({
      docScene: state.documentModel.docScene!,
      docId: state.documentModel.docId!,
      docPlayerDataMap: state.documentModel.docPlayerDataMap,
    }),
  );

  // 当前文档Tag数据
  const docPlayerData = useMemo(() => {
    if (!docId) return undefined;
    return docPlayerDataMap[docId];
  }, [docId, docPlayerDataMap]);

  // 更新播放器状态
  const updatePlayerStatus = useCallback(
    async (
      status: Partial<
        Pick<
          iDocPlayerData,
          // 基础状态
          | 'playerMode'
          | 'playerCurtTime'
          | 'playerIsPlaying'
          | 'playerMuted'
          | 'playerVolume'
          | 'playerRate'
          // 播放器状态记录
          | 'playerRecordTime'
          | 'playerRecordTimeTipOpen'
          // 业务状态
          | 'showSubtitle'
          | 'showSubtitleSpeaker'
          | 'skipBlankSegment'
          | 'subtitlesModel'
          // 样式状态
          | 'videoPlayerHeight'
          | 'videoPlayerWidth'
        >
      >,
    ) => {
      if (!docId || !docScene) return;
      return await dispatch(
        docPlayerActions.changeDocPlayerStatusAction(
          {
            docId,
            docScene,
            data: status,
          },
          true,
        ),
      );
    },
    [docId, docScene, dispatch],
  );
  // 切换播放器
  const togglePlayer = useCallback(
    async (playerMode: 'video' | 'audio') => {
      return await dispatch(
        docPlayerActions.changeDocPlayerStatusAction(
          {
            docId,
            docScene,
            data: {
              playerMode,
            },
          },
          true,
        ),
      );
    },
    [docId, docScene, dispatch],
  );

  return {
    // data Hooks
    docPlayerData,
    updatePlayerStatus,
    // data Function
    togglePlayer,
  };
};
