import axios from "axios";
import parsePhoneNumber from "libphonenumber-js";
import { all, call, put, select, takeLatest } from "redux-saga/effects";
import { logImEXEvent } from "../../firebase/firebase.utils";
import {
  CONVERSATION_ID_BY_PHONE,
  CREATE_CONVERSATION
} from "../../graphql/conversations.queries";
import { INSERT_CONVERSATION_TAG } from "../../graphql/job-conversations.queries";
import client from "../../utils/GraphQLClient";
import { selectBodyshop } from "../user/user.selectors";
import {
  sendMessageFailure,
  sendMessageSuccess,
  setSelectedConversation
} from "./messaging.actions";
import MessagingActionTypes from "./messaging.types";

export function* onToggleChatVisible() {
  yield takeLatest(MessagingActionTypes.TOGGLE_CHAT_VISIBLE, toggleChatLogging);
}
export function* toggleChatLogging() {
  try {
    yield logImEXEvent("messaging_toggle_popup");
  } catch (error) {
    console.log("Error in sendMessage saga.", error);
  }
}
export function* onOpenChatByPhone() {
  yield takeLatest(MessagingActionTypes.OPEN_CHAT_BY_PHONE, openChatByPhone);
}
export function* openChatByPhone({ payload }) {
  logImEXEvent("messaging_open_by_phone");
  const { phone_num, jobid } = payload;

  const p = parsePhoneNumber(phone_num, "CA");
  const bodyshop = yield select(selectBodyshop);
  try {
    const {
      data: { conversations },
    } = yield client.query({
      query: CONVERSATION_ID_BY_PHONE,
      variables: { phone: p.number },
    });

    if (conversations.length === 0) {
      const {
        data: {
          insert_conversations: { returning: newConversationsId },
        },
      } = yield client.mutate({
        mutation: CREATE_CONVERSATION,
        variables: {
          conversation: [
            {
              phone_num: p.number,
              bodyshopid: bodyshop.id,
              job_conversations: jobid ? { data: { jobid: jobid } } : null,
            },
          ],
        },
      });
      yield put(setSelectedConversation(newConversationsId[0].id));
    } else if (conversations.length === 1) {
      //got the ID. Open it.
      yield put(setSelectedConversation(conversations[0].id));

      //Check to see if this job ID is already a child of it. If not add the tag.
      if (
        jobid &&
        !conversations[0].job_conversations.find((jc) => jc.jobid === jobid)
      )
        yield client.mutate({
          mutation: INSERT_CONVERSATION_TAG,
          variables: {
            conversationId: conversations[0].id,
            jobId: jobid,
          },
        });
    } else {
      console.log("ERROR: Multiple conversations found. ");
    }
  } catch (error) {
    console.log("Error in sendMessage saga.", error);
  }
}

export function* onSendMessage() {
  yield takeLatest(MessagingActionTypes.SEND_MESSAGE, sendMessage);
}
export function* sendMessage({ payload }) {
  try {
    const response = yield call(axios.post, "/sms/send", payload);
    if (response.status === 200) {
      yield put(sendMessageSuccess(payload));
    } else {
      yield put(sendMessageFailure(response.data));
    }
  } catch (error) {
    console.log("Error in sendMessage saga.", error);
    yield put(sendMessageFailure(error));
  }
}

export function* messagingSagas() {
  yield all([
    call(onSendMessage),
    call(onOpenChatByPhone),
    call(onToggleChatVisible),
  ]);
}
