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

//strings
import strings from "../constants/localization";

//actions
import {
  threadCreateWithExistThread,
  threadJoinPublicGroup,
  threadNew
} from "../actions/threadActions";
import {chatModalPrompt} from "../actions/chatActions";

//components
import {ROUTE_INDEX} from "../constants/routes";
import Text from "../../../Talk-ui-kit/src/typography/Text";
import Paper from "../../../Talk-ui-kit/src/paper";
import Gap from "../../../Talk-ui-kit/src/gap";

//styling

//statics

//functions

@connect(store => {
  return {
    chatInstance: store.chatInstance.chatSDK,
  };
}, null, null, {forwardRef: true})
class ModalJoin extends Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const {location, history, dispatch} = this.props;
    const {tn: threadName} = queryString.parse(location.search, {ignoreQueryPrefix: true});
    if (threadName) {
      const extraMessage = message => (
        <Fragment>
          <Gap y={5} block/>
          <Paper colorBackground style={{borderRadius: "5px"}}>
            <Text size="xs">{message}</Text>
          </Paper>
        </Fragment>
      );
      dispatch(chatModalPrompt(true, `${strings.areYouSureAboutJoiningThisThread}؟`, () => {
        history.push(ROUTE_INDEX);
        dispatch(threadJoinPublicGroup(threadName)).then(e => {
          if (e.hasError) {
            dispatch(chatModalPrompt());
            dispatch(chatModalPrompt(true, `${strings.hasFollowingErrorWhileJoining}`, null, e => {
              dispatch(chatModalPrompt());
            }, null, null, extraMessage(e.errorMessage), true));
            return;
          }
          const {chatInstance} = this.props;
          chatInstance.getThreadInfo({threadIds: [e.result.id]}).then(thread => {
            dispatch(threadCreateWithExistThread(thread));
            dispatch(threadNew(thread))
          });
        });
        dispatch(chatModalPrompt());
      }, e => {
        history.push(ROUTE_INDEX);
      }, strings.yes, null, extraMessage(threadName)));
    } else {
      history.push(ROUTE_INDEX);
    }
  }

  onClose() {
    this.setState({
      showing: false
    });
  }

  render() {
    return null
  }
}

export default withRouter(ModalJoin);