import { all, call, put, takeLatest } from "redux-saga/effects";
import {
  auth,
  getCurrentUser,
  updateCurrentUser
} from "../../firebase/firebase.utils";
import {
  signInFailure,
  signInSuccess,
  signOutFailure,
  signOutSuccess,
  unauthorizedUser,
  updateUserDetailsSuccess
} from "./user.actions";
import UserActionTypes from "./user.types";

// export function* getSnapshotFromUserAuth(userAuth) {
//   try {
//     const userRef = yield call(createUserProfileDocument, userAuth);
//     //const userSnapshot = yield userRef.get();
//   } catch (error) {
//     yield put(signInFailure(error));
//   }
// }

export function* signInWithEmail({ payload: { email, password } }) {
  try {
    const { user } = yield auth.signInWithEmailAndPassword(email, password);
    let token = yield user.getIdToken();
    localStorage.setItem("token", token);
    window.sessionStorage.setItem(`lastTokenRefreshTime`, new Date());
    yield put(
      signInSuccess({
        uid: user.uid,
        email: user.email,
        displayName: user.displayName,
        photoURL: user.photoURL,
        authorized: true
      })
    );
  } catch (error) {
    yield put(signInFailure(error));
  }
}
//This is the listener fo rthe call, and when it finds it, it triggers somethign else.
export function* onEmailSignInStart() {
  yield takeLatest(UserActionTypes.EMAIL_SIGN_IN_START, signInWithEmail);
}

export function* isUserAuthenticated() {
  try {
    const user = yield getCurrentUser();
    if (!user) {
      yield put(unauthorizedUser());
      return;
    }
    let token = yield user.getIdToken();
    localStorage.setItem("token", token);
    window.sessionStorage.setItem(`lastTokenRefreshTime`, new Date());

    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* signOutStart() {
  try {
    yield auth.signOut();
    yield put(signOutSuccess());
    localStorage.removeItem("token");
  } catch (error) {
    yield put(signOutFailure(error.message));
  }
}

export function* onSignOutStart() {
  yield takeLatest(UserActionTypes.SIGN_OUT_START, signOutStart);
}

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* userSagas() {
  yield all([
    call(onEmailSignInStart),
    call(onCheckUserSession),
    call(onSignOutStart),
    call(onUpdateUserDetails)
  ]);
}
