import React, {Component} from "react";
import {connect} from "react-redux";
import {withRouter} from "react-router-dom";

//strings
import strings from "../../constants/localization";
import {CHAT_CALL_BOX_NORMAL, MAX_GROUP_CALL_COUNT} from "../../constants/callModes";


//actions
import {
  chatCallBoxShowing,
  chatCallGetParticipantList,
  chatSelectParticipantForCallShowing,
  chatStartGroupCall,
  chatStartCall, chatModalCallError
} from "../../actions/chatActions";

//UI components
import {Button} from "../../../../Talk-ui-kit/src/button"
import Container from "../../../../Talk-ui-kit/src/container";
import {Text} from "../../../../Talk-ui-kit/src/typography";
import {MdPhone} from "react-icons/md";

//styling
import style from "../../../styles/utils/ghost.scss";
import {threadCreateWithExistThread} from "../../actions/threadActions";
import {checkForParticipantsStatus, hasPermissionErrorInCall, resetChatCall} from "../../utils/helpers";
import {getName} from "./contactList";

function getTitleForThread(selectedParticipant) {
  const map = selectedParticipant.map(participant => getName(participant))
  if (map.length > 3) {
    return strings.callWithContacts(map.slice(0, 3).join(", "), true);
  }
  return strings.callWithContacts(map.join(", "));
}

function getDescriptionForThread(selectedParticipant) {
  const title = getTitleForThread(selectedParticipant);
  return strings.callWithContactsDesc(title);
}

@connect(store => {
  return {
    user: store.user.user,
    chatCallStatus: store.chatCallStatus
  };
}, null, null, {forwardRef: true})
export default class MakeGlobalCall extends Component {

  constructor(props) {
    super(props);
    this.onMakeCall = this.onMakeCall.bind(this);
    this._selectParticipantForCallFooterFragment = this._selectParticipantForCallFooterFragment.bind(this);
  }

  _selectParticipantForCallFooterFragment(callType, mode, {selectedContacts, allContacts}) {
    const {dispatch, user} = this.props;
    const isMaximumCount = (selectedContacts && selectedContacts.length > MAX_GROUP_CALL_COUNT - 1);
    return <Container>
      <Container>
        {(selectedContacts && selectedContacts.length >= 1) &&
        <Button disabled={isMaximumCount} color={isMaximumCount ? "gray" : "accent"} onClick={e => {
          if (isMaximumCount) {
            return;
          }
          dispatch(chatSelectParticipantForCallShowing(false));
          let selectedParticipants = allContacts.filter(e => selectedContacts.indexOf(e.id) > -1);
          const invitees = selectedParticipants.map(e => ({
            id: e.id,
            idType: mode === "CONTACT" ? "TO_BE_USER_CONTACT_ID" : "TO_BE_USER_ID"
          }));
          if (invitees.length <= 1) {
            return dispatch(chatStartCall(null, callType || "VOICE", {invitees}, result => {
              if (hasPermissionErrorInCall(result)) {
                resetChatCall(dispatch);
                return dispatch(chatModalCallError(true, result));
              }
              dispatch(chatCallBoxShowing(CHAT_CALL_BOX_NORMAL, result, selectedParticipants[0]));
              dispatch(chatCallGetParticipantList(null, selectedParticipants));
            }))
          }
          dispatch(chatStartGroupCall(null, invitees, callType || "VOICE",
            {
              threadInfo: {
                title: getTitleForThread(selectedParticipants),
                description: getDescriptionForThread(selectedParticipants)
              }
            }, result => {
              if (hasPermissionErrorInCall(result)) {
                resetChatCall(dispatch);
                return dispatch(chatModalCallError(true, result));
              }
              selectedParticipants.push(user);
              if (mode === "CONTACT") {
                selectedParticipants = selectedParticipants.map(participant => (participant.id === user.id ? participant : {
                  ...participant, ...participant.linkedUser,
                  id: participant.userId,
                  contactId: participant.id
                }));
              }
              dispatch(threadCreateWithExistThread(result));
              dispatch(chatCallBoxShowing(CHAT_CALL_BOX_NORMAL, result));
              dispatch(chatCallGetParticipantList(null, selectedParticipants));
              checkForParticipantsStatus.call(this, selectedParticipants);
            }));
        }}>{strings.call}</Button>
        }

        <Button text onClick={() => dispatch(chatSelectParticipantForCallShowing(false))}>{strings.cancel}</Button>
      </Container>
      <Container>
        {
          isMaximumCount &&
          <Text color="accent">{strings.maximumNumberOfContactSelected}</Text>
        }
      </Container>
    </Container>
  }

  onMakeCall(callType, params) {
    return this.props.dispatch(chatSelectParticipantForCallShowing({
        showing: true,
        selectiveMode: true,
        headingTitle: strings.forCallPleaseSelectContacts,
        FooterFragment: this._selectParticipantForCallFooterFragment.bind(this, callType),
        ...params
      },
    ));
  }

  render() {
    const {noRender, chatCallStatus} = this.props;
    if (noRender) {
      return null;
    }
    return (<Container onClick={chatCallStatus.status ? null : this.onMakeCall.bind(this, "VOICE")}>
      <MdPhone size={style.iconSizeMd} color={chatCallStatus.status ? "rgb(255 255 255 / 30%)" : style.colorWhite}/>
    </Container>)
  }
}