import { all, call, put, takeLatest } from "redux-saga/effects";
import {
  auth,
  getCurrentUser,
  updateCurrentUser,
} from "../../firebase/firebase.utils";
import { QUERY_BODYSHOP } from "../../graphql/bodyshop.queries";
import client from "../../graphql/GraphQLClient";
import { UPSERT_USER } from "../../graphql/user.queries";
import ipcTypes from "../../ipc.types";
import {
  sendPasswordResetFailure,
  sendPasswordResetSuccess,
  setBodyshop,
  signInFailure,
  signInSuccess,
  signOutFailure,
  signOutSuccess,
  unauthorizedUser,
  updateUserDetailsSuccess,
  validatePasswordResetFailure,
  validatePasswordResetSuccess,
} from "./user.actions";
import UserActionTypes from "./user.types";

const { ipcRenderer } = window;

export function* onEmailSignInStart() {
  yield takeLatest(UserActionTypes.EMAIL_SIGN_IN_START, signInWithEmail);
}
export function* signInWithEmail({ payload: { email, password } }) {
  try {
    const { user } = yield auth.signInWithEmailAndPassword(email, password);

    const result = yield client.mutate({
      mutation: UPSERT_USER,
      variables: { authEmail: user.email, authToken: user.uid },
    });
    console.log("function*signInWithEmail -> result", result);

    yield put(
      signInSuccess({
        uid: user.uid,
        email: user.email,
        displayName: user.displayName,
        photoURL: user.photoURL,
        authorized: true,
      })
    );
  } catch (error) {
    yield put(signInFailure(error));
  }
}

export function* onCheckUserSession() {
  yield takeLatest(UserActionTypes.CHECK_USER_SESSION, isUserAuthenticated);
}
export function* isUserAuthenticated() {
  try {
    const user = yield getCurrentUser();
    if (!user) {
      yield put(unauthorizedUser());
      return;
    }

    yield put(
      signInSuccess({
        uid: user.uid,
        email: user.email,
        displayName: user.displayName,
        photoURL: user.photoURL,
        authorized: true,
      })
    );
  } catch (error) {
    yield put(signInFailure(error));
  }
}
export function* onSignOutStart() {
  yield takeLatest(UserActionTypes.SIGN_OUT_START, signOutStart);
}
export function* signOutStart() {
  try {
    ipcRenderer.send(ipcTypes.default.fileWatcher.toMain.stop);
    yield auth.signOut();
    yield put(signOutSuccess());
    localStorage.removeItem("token");
  } catch (error) {
    yield put(signOutFailure(error.message));
  }
}

export function* onUpdateUserDetails() {
  yield takeLatest(UserActionTypes.UPDATE_USER_DETAILS, updateUserDetails);
}
export function* updateUserDetails(userDetails) {
  try {
    yield updateCurrentUser(userDetails.payload);
    yield put(updateUserDetailsSuccess(userDetails.payload));
  } catch (error) {
    //yield put(signOutFailure(error.message));
    //TODO error handling
  }
}

export function* onSignInSuccess() {
  yield takeLatest(UserActionTypes.SIGN_IN_SUCCESS, signInSuccessSaga);
}

export function* signInSuccessSaga({ payload }) {
  //Query for the Correct Bodyshop

  const shop = yield client.query({ query: QUERY_BODYSHOP });

  yield put(setBodyshop(shop.data.bodyshops[0]));

  ipcRenderer.send(ipcTypes.default.fileWatcher.toMain.start);
  // LogRocket.identify(payload.email);
  // if (!payload.email.includes("@imex.")) yield put(setInstanceId(payload.uid));
  // yield logImEXEvent("redux_sign_in_success");
}

export function* onSendPasswordResetStart() {
  yield takeLatest(
    UserActionTypes.SEND_PASSWORD_RESET_EMAIL_START,
    sendPasswordResetEmail
  );
}
export function* sendPasswordResetEmail({ payload }) {
  try {
    yield auth.sendPasswordResetEmail(payload, {
      url: "https://imex.online/passwordreset",
    });

    yield put(sendPasswordResetSuccess());
  } catch (error) {
    yield put(sendPasswordResetFailure(error.message));
  }
}

export function* onValidatePasswordResetStart() {
  yield takeLatest(
    UserActionTypes.VALIDATE_PASSWORD_RESET_START,
    validatePasswordResetStart
  );
}
export function* validatePasswordResetStart({ payload: { password, code } }) {
  try {
    yield auth.confirmPasswordReset(code, password);
    yield put(validatePasswordResetSuccess());
  } catch (error) {
    console.log("function*validatePasswordResetStart -> error", error);
    yield put(validatePasswordResetFailure(error.message));
  }
}

export function* userSagas() {
  yield all([
    call(onEmailSignInStart),
    call(onCheckUserSession),
    call(onSignOutStart),
    call(onUpdateUserDetails),
    call(onSignInSuccess),
    call(onSendPasswordResetStart),
    call(onValidatePasswordResetStart),
  ]);
}
