import React, { useState, useCallback, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import PlyrPlayer from '../components/public/PlyrPlayer';
import PdfPlayer from '../components/public/PdfPlayer';
import { useTranslation } from 'react-i18next';
import FPlatformEnum from '../utils/enum';

export default function MediaPlayer() {
  // 解码 base64 化的视频 url:
  // 例如 aHR0cDovL3NmMS1oc2Nkbi10b3MucHN0YXRwLmNvbS9vYmovbWVkaWEtZmUveGdwbGF5ZXJfZG9jX3ZpZGVvL2Zsdi94Z3BsYXllci1kZW1vLTM2MHAuZmx2
  // 解码结果是 http://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-360p.flv
  const decodeFileUrl = (url) => {
    const decodedUrl = atob(url);
    return decodedUrl;
  };
  const { fileUrl, platform, language } = useParams();
  const [isShowPdf, setShowPdf] = useState(true);
  const { t, i18n } = useTranslation();

  const [plyrProps, setPlyrProps] = useState({
    source: {
      type: 'video',
      title: 'Example Video',
      sources: [
        {
          src: decodeFileUrl(fileUrl),
          type: 'video/mp4',
          size: 720,
        },
      ],
    }, // https://github.com/sampotts/plyr#the-source-setter
    options: {
      playsinline: false,
    }, // https://github.com/sampotts/plyr#options
  });

  useEffect(() => {
    i18n.changeLanguage(language);
  }, [i18n, language]);

  useEffect(() => {
    setShowPdf(decodeFileUrl(fileUrl).endsWith('.pdf'));
    setPlyrProps({
      source: {
        type: 'video',
        title: 'Video',
        sources: [
          {
            src: decodeFileUrl(fileUrl),
            type: 'video/mp4',
            size: 720,
          },
        ],
      },
      options: {
        autoplay: true,
        i18n: {
          speed: t('播放速度'),
          normal: t('正常'),
        },
        speed: {
          selected: 1,
          options: [2, 1.5, 1.25, 1, 0.5],
        },
      }, // https://github.com/sampotts/plyr#options
    });
  }, [fileUrl]);

  return (
    <div>
      {isShowPdf && (
        <div className={`h-[70vh]`}>
          <PdfPlayer
            courseFileUrl={decodeFileUrl(fileUrl)}
            isShellWeb={FPlatformEnum.byIndex(platform).isShell()}
          />
        </div>
      )}
      {!isShowPdf && (
        <div className='border plyr-wrapper'>
          <PlyrPlayer plyrProps={plyrProps} />
        </div>
      )}
    </div>
  );
}
