import React, {useRef, useEffect, useMemo} from 'react';
import Icon from './icon';
import './video-player.scss';
import { AgoraElectronStream, StreamType, nativeRTCClient as nativeClient } from '../utils/agora-electron-client';
import { useRoomState } from '../containers/root-container';
import { platform } from '../utils/platform';
import ArrowDownwardIcon from '@material-ui/icons/ArrowDownward';
import {makeStyles} from '@material-ui/core/styles';
import {roomStore} from "../stores/room";
import BuildIcon from '@material-ui/icons/Build';
// import {eventBus} from "../stores/EventBus";
// import StarIcon from '@material-ui/icons/Star';
// import EmojiEventsOutlinedIcon from '@material-ui/icons/EmojiEventsOutlined';
import UserStars from './user-stars';
import AddStarsButton, {StarsButtonType} from "./add-stars-btn";
import HandsUpIcon from "./hands-up-icon";

const useStyles = makeStyles({
  stageDown : {
    display: 'flex',
    marginLeft: 2,
    marginRight: 2,
    width: 20,
    height: 24,
    color: '#fff',
    lineHeight: 24,
    opacity: .8,
    cursor:'pointer'
  },
  fixStream: {
    marginLeft: 4,
    marginRight: 4,
    width: 16,
    height: 24,
    color: '#fff',
    lineHeight: 24,
    opacity: .8,
    cursor:'pointer'
  },
  star: {
    height: 20,
    color: '#ebb445'
  },
  emojiEvent: {
    width: 18,
    marginLeft: 3,
    marginRight: 3,
    height: 24,
    color: '#fff',
    lineHeight: 24,
    opacity: .8,
    cursor:'pointer'
  }
});


const contentMode = 0;

interface VideoPlayerProps {
  domId?: string
  id?: string
  streamID: number
  preview?: boolean
  account?: any
  stream?: any
  role?: string
  audio?: boolean
  video?: boolean
  className?: string
  showProfile?: boolean
  local?: boolean
  handleClick?: (type: string, streamID: number, uid: string) => Promise<any>
  close?: boolean
  handleClose?: (uid: string, streamID: number) => void
}

let reloadStreamTimer: number | null = null;

const VideoPlayer: React.FC<VideoPlayerProps> = ({
  preview,
  role,
  account,
  stream,
  className,
  domId,
  streamID,
  audio,
  id,
  video,
  handleClick,
  local,
  handleClose,
  close
}) => {
  const style = useStyles();
  const loadVideo = useRef<boolean>(false);
  const loadAudio = useRef<boolean>(false);

  const stateError  = useRef<boolean>(false);



  // const hasError = useMemo(() => {
  //   return stateError.current;
  // }, [stateError]);

  const lockPlay = useRef<boolean>(false);

  const AgoraRtcEngine = useMemo(() => {
    return nativeClient.rtcEngine;
    // eslint-disable-next-line
  }, [nativeClient.rtcEngine]);

  useEffect(() => {
    if (!domId || !stream || !nativeClient) return;
    if (platform === 'electron') {
      const _stream = stream as AgoraElectronStream;
      const dom = document.getElementById(domId);
      if (!dom) return;
      console.log("[agora-electron] video player", dom, streamID, contentMode);
      if (preview) {
        // set for preview
        AgoraRtcEngine.setupLocalVideo(dom);
        AgoraRtcEngine.setupViewContentMode(streamID, contentMode);
        AgoraRtcEngine.setClientRole(1);
        // preview mode required you become host
        AgoraRtcEngine.startPreview();
        // AgoraRtcEngine.muteLocalVideoStream(nativeClient.published);
        // AgoraRtcEngine.muteLocalAudioStream(nativeClient.published);
        return () => {
          console.log("[agora-electron] stop preview", dom, streamID, contentMode);
          AgoraRtcEngine.stopPreview();
          AgoraRtcEngine.setClientRole(2);
        }
      }
      if (_stream.type === StreamType.local) {
        console.log("[agora-electron] video-player play " ,AgoraRtcEngine.setupViewContentMode(streamID, contentMode));
        console.log("[agora-electron] video-player setupLocalVideo ", AgoraRtcEngine.setupLocalVideo(dom));
        return () => {
          // AgoraRtcEngine.destroyRenderView(streamID, dom, (err: any) => { console.warn(err.message) });
        }
      }

      if (_stream.type === StreamType.localVideoSource) {
        AgoraRtcEngine.setupLocalVideoSource(dom);
        AgoraRtcEngine.setupViewContentMode('videosource', contentMode);
        AgoraRtcEngine.setupViewContentMode(streamID, contentMode);
        return () => {
          // AgoraRtcEngine.destroyRenderView('videosource');
          // AgoraRtcEngine.destroyRenderView(streamID, dom, (err: any) => { console.warn(err.message) });
        }
      }

      if (_stream.type === StreamType.remote) {
        AgoraRtcEngine.subscribe(streamID, dom);
        AgoraRtcEngine.setupViewContentMode(streamID, contentMode);
        return () => {
          // AgoraRtcEngine.destroyRenderView(streamID, dom, (err: any) => { console.warn(err.message) });
        }
      }

      if (_stream.type === StreamType.remoteVideoSource) {
        AgoraRtcEngine.subscribe(streamID, dom);
        AgoraRtcEngine.setupViewContentMode('videosource', contentMode);
        AgoraRtcEngine.setupViewContentMode(streamID, contentMode);
        return () => {
          // AgoraRtcEngine.destroyRenderView('videosource');
          // AgoraRtcEngine.destroyRenderView(streamID, dom, (err: any) => { console.warn(err.message) });
        }
      }
    }
    // eslint-disable-next-line
  }, [domId, stream, AgoraRtcEngine]);


  useEffect(() => {
    if (platform === 'web') {
      if (!stream || !domId || (lockPlay.current && stream.isPlaying())) return;
      lockPlay.current = true;
      /*const playFn = () => {
        if (reloadStreamTimer) {
          clearTimeout(reloadStreamTimer)
          reloadStreamTimer = null;
        }
        reloadStreamTimer = window.setTimeout(() => {
          stream.play(`${domId}`, { fit: 'cover' }, (err: any) => {
            console.log('reloadStreamTimer reloadStreamTimer reloadStreamTimer')
            lockPlay.current = false;
            if (err && err.status !== 'aborted') {
              // 播放失败，一般为浏览器策略阻止。引导用户用手势触发恢复播放。
              console.warn('[video-player] ', err, id);
              if (stream.isPlaying()) {
                stream.stop();
              }
              playFn();
            }
          })
        }, 1000)

      }*/
      stream.play(`${domId}`, { fit: 'cover' }, (err: any) => {
        // console.log('reloadStreamTimer reloadStreamTimer reloadStreamTimer')
        lockPlay.current = false;
        if (err && err.status !== 'aborted') {
          lockPlay.current = true;
          // 播放失败，一般为浏览器策略阻止。引导用户用手势触发恢复播放。
          console.warn('[video-player] ', err, id);
          stateError.current = true;
          // @ts-ignore
          window.errorPlayer = stream;
        }
      })
      return () => {
        // console.log(2343454567,local, streamID, me)
        if (reloadStreamTimer) {
          clearTimeout(reloadStreamTimer)
          reloadStreamTimer = null;
        }
        if (stream.isPlaying()) {

            stream.stop();
          // stream.stop();
        }
        local && stream && stream.close();
      }
    }
    // eslint-disable-next-line
  }, [domId, stream]);

  /*
  const [star, setStar]  = useState<number>(0);
  useEffect(() => {
    console.log('roomStore.state.userStars change')
    if (id) {
      const u = roomStore.state.users.get(id)
      if (u) {
        setStar(u.stars || 0);
      }
    }
    // setStar()
  }, [roomStore.state.users]);
  */

  useEffect(() => {
    if (stream && platform === 'web') {
      // prevent already muted audio
      if (!loadAudio.current) {
        if (!audio) {
          stream.muteAudio();
          console.log('strea mute audio');
        }
        loadAudio.current = true;
        return;
      }

      if (audio) {
        console.log('stream unmute audio');
        stream.unmuteAudio();
      } else {
        console.log('stream mute audio');
        stream.muteAudio();
      }
    }

    if (stream && platform === 'electron') {
      // prevent already muted video
      if (!loadAudio.current) {
        if (!audio) {
          const res = AgoraRtcEngine.muteLocalAudioStream(true);
          console.log("[agora-electron] muteLocalAudioStream(true); ", res);
        }
        loadAudio.current = true;
        return;
      }

      if (audio) {
        const res = AgoraRtcEngine.muteLocalAudioStream(false);
        console.log("[agora-electron] muteLocalAudioStream(false); ", res);
      } else {
        const res = AgoraRtcEngine.muteLocalAudioStream(true);
        console.log("[agora-electron] muteLocalAudioStream(true); ", res);
      }
  }
    // eslint-disable-next-line
  }, [stream, audio, AgoraRtcEngine]);

  useEffect(() => {
    if (stream && platform === 'web') {
      // prevent already muted video
      if (!loadVideo.current) {
        if (!video) {
          console.log('stream mute video');
          stream.muteVideo();
        }
        loadVideo.current = true;
        return;
      }

      if (video) {
        console.log('stream unmute video');
        stream.unmuteVideo();
      } else {
        console.log('stream mute video');
        stream.muteVideo();
      }
    }

    if (stream && platform === 'electron') {
        // prevent already muted video
        if (!loadVideo.current) {
          if (!video) {
            const res = AgoraRtcEngine.muteLocalVideoStream(true);
            console.log("[agora-electron] muteLocalVideoStream(true); ", res);
          }
          loadVideo.current = true;
          return;
        }

        if (video) {
          const res = AgoraRtcEngine.muteLocalVideoStream(false);
          console.log("[agora-electron] muteLocalVideoStream(false); ", res);
        } else {
          const res = AgoraRtcEngine.muteLocalVideoStream(true);
          console.log("[agora-electron] muteLocalVideoStream(true); ", res);
        }
    }
    // eslint-disable-next-line
  }, [stream, video, AgoraRtcEngine]);

  const onAudioClick = (evt: any) => {
    if (handleClick && id) {
      handleClick('audio', streamID, id);
    }
  }
  const onStageDownClick = (evt: any) => {
    if (handleClick && id) {
      handleClick('stageDown', streamID, id);
    }
  }

  const fixUserStream = (evt: any) => {
    if (handleClick && id) {
      handleClick('fixUserStream', streamID, id);
    }
  }


  const onVideoClick = (evt: any) => {
    if (handleClick && id) {
      handleClick('video', streamID, id);
    }
  }

  const onClose = (evt: any) => {
    if (handleClose && id) {
      handleClose('close', streamID);
    }
  }
  // const addStar = (evt: any) => {
  //   if (me.role != 'teacher') {
  //     return
  //   }
  //   eventBus.emit('showAddStartDialog', {uid: id});
  // }
  // const resumeStream = (evt: any) => {
  //   stateError.current = false;
  //   stream.resume()
  // }

  const me = useRoomState().me;
  const teacherId = useRoomState().course.teacherId;
  // let stu = useRoomState().users.get(`${id}`);
return (
  <div className={`${className ? className : (preview ? 'preview-video' : `agora-video-view ${Boolean(video) === false && stream ? 'show-placeholder' : ''}`)}`}>

    {close ? <div className="icon-close" onClick={onClose}></div> : null}
    {className !== 'screen-sharing' ? <div className={role === 'teacher' ? 'teacher-placeholder' : 'student-placeholder'}></div> : null }
    {preview ? null :
      account ?
        <>
          { streamID > 0 && id !== teacherId?
            <>
              <UserStars id={id} streamID={streamID}></UserStars>
              <div className="hands-wrapper">
                <HandsUpIcon id={id} streamID={streamID}></HandsUpIcon>
              </div>

            </>
            /*<div className='star'>
              <div className="medal"></div>
              <div className="medal-bg">
                <span className="points">
                  {star}
                </span>
              </div>
            </div> */: null }
        <div className="video-profile">
          <span className="account">{account}</span>
          {/*{stateError.current?<span  onClick={resumeStream}>恢复</span>: null}*/}
          {streamID <= 0 ? null :
            <>
            {
              /*me.uid === id ||*/ me.role === 'teacher'
                ? <span className="media-btn">

                    <>

                    {id !== roomStore.state.course.teacherId
                        ?
                      <>
                        {/*<EmojiEventsOutlinedIcon  onClick={addStar} className={style.emojiEvent}></EmojiEventsOutlinedIcon>*/}
                        <AddStarsButton type={StarsButtonType.SMALL} uid={streamID}></AddStarsButton>
                        <ArrowDownwardIcon onClick={onStageDownClick} className={style.stageDown}></ArrowDownwardIcon>
                      </>
                        :<BuildIcon onClick={fixUserStream} className={style.fixStream}></BuildIcon>}



                    <Icon onClick={onAudioClick} className={audio ? "icon-speaker-on" : "icon-speaker-off"}
                          data={"audio"}/>
                    < Icon onClick = {onVideoClick} className={video ? "icons-camera-unmute-s" : "icons-camera-mute-s"}
                    data={"video"}/>
                    </>
              </span>
                : <span className="media-btn">
                <Icon className={audio ? "icon-speaker-on disabled" : "icon-speaker-off disabled"} data={"audio"}/>
                <Icon className={video ? "icons-camera-unmute-s disabled" : "icons-camera-mute-s disabled"}
                      data={"video"}/>
              </span>
            }</>

          }



        </div>
        </>
        : null
    }

    <div id={`${domId}`} className={`agora-rtc-video ${local && platform === 'electron' ? 'rotateY180deg' : ''}`}></div>
  </div>
)
}

export default React.memo(VideoPlayer);
