import React, { useRef, useEffect, useMemo } from 'react';
// import Icon from './icon';
import './member-holder.scss';
import { nativeRTCClient as nativeClient } from '../utils/agora-electron-client';
import { useRoomState } from '../containers/root-container';
import { platform } from '../utils/platform';
import AccountCircle from '@material-ui/icons/AccountCircle';
import Link from '@material-ui/core/Link';
// import PanToolIcon from '@material-ui/icons/PanTool';
// import {roomStore} from "../stores/room";
import UserStars from "./user-stars";
// import {eventBus} from "../stores/EventBus";
import AddStarsButton, { StarsButtonType } from './add-stars-btn';
import HandsUpIcon from "./hands-up-icon";
// const contentMode = 0;

interface MemberHolderProps {
  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>
  handleClose?: (uid: string, streamID: number) => void
}

const MemberHolder: React.FC<MemberHolderProps> = ({
  role,
  account,
  stream,
  className,
  streamID,
  audio,
  id,
  video,
  handleClick,
  handleClose,
}) => {
  const loadVideo = useRef<boolean>(false);
  const loadAudio = useRef<boolean>(false);

  // 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 (_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) });
        }
      }
    }
  }, [domId, stream, AgoraRtcEngine]);

  useEffect(() => {
    if (platform === 'web') {
      if (!stream || !domId || lockPlay.current && stream.isPlaying()) return;
      lockPlay.current = true;
      stream.play(`${domId}`, { fit: 'cover' }, (err: any) => {
        lockPlay.current = false;
        if (err && err.status !== 'aborted') {
          console.warn('[video-player] ', err, id);
        }
      })
      return () => {
        if (stream.isPlaying()) {
          stream.stop();
        }
        local && stream && stream.close();
      }
    }
  }, [domId, stream]);
  */

  // const isHandUp = useMemo(() => {
  //   const hu = roomStore.state.handsUpStudents[streamID];
  //   console.log(streamID, hu)
  //   return hu
  // }, [roomStore.state.handsUpStudents]);

  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);
      }
  }
  }, [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);
        }
    }
  }, [stream, video, AgoraRtcEngine]);
  /*
  const onAudioClick = (evt: any) => {
    if (handleClick && id) {
      handleClick('audio', streamID, id);
    }
  }
  */

  const onStageUp = (evt: any) => {
    if (handleClick && id) {
      handleClick('stageUp', 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 me = useRoomState().me;

  return (
    <div className={`${className ? className : `agora-holder-view ${Boolean(video) === false && stream ? 'show-placeholder' : ''}`}`}>
      {/*{className !== 'screen-sharing' ? <div className={role === 'teacher' ? 'teacher-placeholder' : 'student-placeholder'}></div> : null }*/}

        <AccountCircle  className='holder-avatar'></AccountCircle>

      {account ?
        <div className="user-profile">
          <span className="account">{account}</span>
          {/*me.uid === id ||*/}

          {me.role === 'teacher' ?
            <span className="media-btn">

              {/*
                isHandUp ?
                <PanToolIcon className='hands-btn blink'></PanToolIcon>:
                  <div className='hands-btn'></div>
              */}
              <HandsUpIcon id={id} streamID={streamID}></HandsUpIcon>
              <UserStars id={id} streamID={streamID}></UserStars>
              {/*<Link component="button" onClick={onAudioClick}>{audio ? "静音" : "开麦"}</Link>*/}
              {me.role === 'teacher' ?
                <>
                  {/*<Link component="button" onClick={addStar}>奖励</Link>*/}
                  <AddStarsButton type={StarsButtonType.TEXT} uid={streamID}></AddStarsButton>
                  <Link component="button" onClick={onStageUp}>上台</Link>
                </>
                : null}
                {/*<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> : <UserStars id={id} streamID={streamID}></UserStars>}
        </div>
        : null}
    </div>
  )
}

export default React.memo(MemberHolder);
