import React, {Component} from "react";
import {connect} from "react-redux";
import Cookies from "js-cookie";
import classnames from "classnames";
import {
  isGroup,
  isParticipantVideoTurnedOn,
  isRecording,
  isRecordingOwnerIsMe,
  isScreenShare,
  isScreenShareOwnerIsMe,
  sortCallParticipantsBy
} from "../utils/helpers";

//strings
import strings from "../constants/localization";
import {
  CHAT_CALL_STATUS_STARTED,
  GROUP_VIDEO_CALL_VIEW_MODE,
  CALL_SETTINGS
} from "../constants/callModes";

//actions
import {
  chatCallEndScreenShare,
  chatCallStartScreenShare,
  chatStartCallRecording,
  chatStopCallRecording
} from "../actions/chatActions";

//components
import Container from "../../../Talk-ui-kit/src/container";
import {Text} from "../../../Talk-ui-kit/src/typography";
import List, {ListItem} from "../../../Talk-ui-kit/src/list";

import Gap from "../../../Talk-ui-kit/src/gap";
import Modal, {ModalBody, ModalHeader, ModalFooter} from "../../../Talk-ui-kit/src/modal";
import {
  MdOutlineScreenShare,
  MdMicOff,
  MdRingVolume,
  MdVolumeUp,
  MdMic,
  MdVideocam,
  MdMoreHoriz,
  MdViewQuilt,
  MdFeaturedVideo,
  MdViewCarousel,
  MdFiberManualRecord,
  MdPause
} from "react-icons/md";

//styling
import style from "../../styles/app/CallBoxControlSetMore.scss";

//statics

//functions


@connect(store => {
  return {
    chatCallStatus: store.chatCallStatus,
    user: store.user.user,
    chatCallParticipantList: sortCallParticipantsBy(store.chatCallParticipantList.participants, "id")
  }
})
export default class CallBoxControlSetMore extends Component {

  constructor(props) {
    super(props);
    this.onViewModeClick = this.onViewModeClick.bind(this);
    this.shareScreenClick = this.shareScreenClick.bind(this);
    this.onRecordingClick = this.onRecordingClick.bind(this);
    this.onClose = this.onClose.bind(this);
    const currentSettings = JSON.parse(Cookies.get(CALL_SETTINGS.CALL_SETTINGS_COOKIE_KEY_NAME) || "{}");
    this.state = {
      groupVideoCallMode: currentSettings.hasOwnProperty("groupVideoCallMode") ? currentSettings.groupVideoCallMode : GROUP_VIDEO_CALL_VIEW_MODE.GRID_VIEW
    };
    this.event = new CustomEvent(CALL_SETTINGS.CALL_SETTINGS_CHANGE_EVENT, {detail: this.state});
    window.dispatchEvent(this.event);
  }

  setSetting(key, value) {
    const nextState = value || !this.state[key];
    let currentSettings = Cookies.get(CALL_SETTINGS.CALL_SETTINGS_COOKIE_KEY_NAME);
    if (currentSettings) {
      currentSettings = JSON.parse(currentSettings);
    } else {
      currentSettings = {};
    }
    currentSettings[key] = nextState;
    Cookies.set(CALL_SETTINGS.CALL_SETTINGS_COOKIE_KEY_NAME, JSON.stringify(currentSettings), {expires: 9999999999});
    this.setState({
      [key]: nextState
    });
    this.event = new CustomEvent(CALL_SETTINGS.CALL_SETTINGS_CHANGE_EVENT, {detail: currentSettings});
    window.dispatchEvent(this.event);
    this.onClose();
  }

  onViewModeClick() {
    this.setSetting("groupVideoCallMode", this.state["groupVideoCallMode"] === GROUP_VIDEO_CALL_VIEW_MODE.GRID_VIEW ? GROUP_VIDEO_CALL_VIEW_MODE.THUMBNAIL_VIEW : GROUP_VIDEO_CALL_VIEW_MODE.GRID_VIEW);
  }

  shareScreenClick(isSharing) {
    const {dispatch} = this.props;
    dispatch(isSharing ? chatCallEndScreenShare() : chatCallStartScreenShare());
    this.onClose();
  }

  onRecordingClick(isRecording) {
    const {dispatch} = this.props;
    dispatch(isRecording ? chatStopCallRecording() : chatStartCallRecording());
    this.onClose();
  }

  onClose(e) {
    const {onMoreActionClick} = this.props;
    onMoreActionClick(false);
  }

  render() {
    const {chatCallStatus, user, chatCallParticipantList} = this.props;
    const {groupVideoCallMode} = this.state;
    const {status, call} = chatCallStatus;
    const isScreenShareCall = isScreenShare(call);
    const isScreenSharingOwnerIsMeResult = isScreenShareCall && isScreenShareOwnerIsMe(call.screenShare, user);
    const isRecordingCall = isRecording(call);
    const isRecordingCallOwnerIsMe = isRecordingCall && isRecordingOwnerIsMe(call.recording, user);
    const isGroupCall = call.conversationVO && isGroup(call.conversationVO);
    const settingItemClassNames = classnames({
      [style.CallBoxControlSetMore__SettingItemContainer]: true
    });
    const enableRecordingAndScreenSharingFeature = status === CHAT_CALL_STATUS_STARTED;
    const enableCallRecordingFeature = enableRecordingAndScreenSharingFeature && (isRecordingCallOwnerIsMe || !isRecordingCall);
    const isCallRecordingByMe = enableCallRecordingFeature && isRecordingCallOwnerIsMe;

    return <Modal isOpen={true} wrapContent userSelect="none" onClose={this.onClose} onClick={e => e.stopPropagation()}>

      <ModalBody>
        <List>
          {(isGroupCall && isParticipantVideoTurnedOn(call, chatCallParticipantList)) &&
          <ListItem selection invert onSelect={!isScreenShareCall && this.onViewModeClick}>

            <Container className={settingItemClassNames}>

              <Container className={style.CallBoxControlSetMore__SettingItemText}>
                <MdFeaturedVideo size={style.iconSizeMd} color={style.colorGrayDark}/>
                <Gap x={20}>
                  <Text color={isScreenShareCall && "gray"}>{strings.viewModeConfig}</Text>
                </Gap>
              </Container>

              <Container className={style.CallBoxControlSetMore__SettingItemStatus}>
                {groupVideoCallMode === GROUP_VIDEO_CALL_VIEW_MODE.THUMBNAIL_VIEW || isScreenShareCall ?
                  <MdViewCarousel size={style.iconSizeMd} color={style.colorGrayDark}/>
                  :
                  <MdViewQuilt size={style.iconSizeMd} color={style.colorGrayDark}/>
                }

              </Container>

            </Container>
          </ListItem>
          }

          <ListItem selection invert
                    onSelect={enableRecordingAndScreenSharingFeature && this.shareScreenClick.bind(this, isScreenSharingOwnerIsMeResult)}>

            <Container className={settingItemClassNames}>

              <Container className={style.CallBoxControlSetMore__SettingItemText}>
                <MdOutlineScreenShare size={style.iconSizeMd}
                                      color={isScreenSharingOwnerIsMeResult ? style.colorAccent : style.colorGrayDark}/>
                <Gap x={20}>
                  <Text color={!enableRecordingAndScreenSharingFeature && "gray"}>{strings.shareScreen}</Text>
                </Gap>
              </Container>

              <Container className={style.CallBoxControlSetMore__SettingItemStatus}>
                {isScreenSharingOwnerIsMeResult &&
                <MdFiberManualRecord className={style.CallBoxControlSetMore__Recording}/>}
              </Container>

            </Container>
          </ListItem>

          <ListItem selection invert
                    onSelect={enableCallRecordingFeature && this.onRecordingClick.bind(this, isCallRecordingByMe)}>

            <Container className={settingItemClassNames}>

              <Container className={style.CallBoxControlSetMore__SettingItemText}>
                <MdMic size={style.iconSizeMd} color={isCallRecordingByMe ? style.colorAccent : style.colorGrayDark}/>
                <Gap x={20}>
                  <Text color={(!enableCallRecordingFeature) && "gray"}>{strings.recordCallSession}</Text>
                </Gap>
              </Container>
              <Container className={style.CallBoxControlSetMore__SettingItemStatus}>
                {isCallRecordingByMe && <MdFiberManualRecord className={style.CallBoxControlSetMore__Recording}/>}
              </Container>
            </Container>
          </ListItem>
        </List>
      </ModalBody>
    </Modal>
  }
}