
import { call, put } from "redux-saga/effects";
import { userLoggedIn, requestLoginFailure, userLoggedOut } from "../actions/auth";
import {
  fetchCurrentUserRequest,
  fetchCurrentUserSuccess, fetchCurrentUserFailure,
  subscribeToNewsletterSuccess, subscribeToNewsletterFailure,
  registerUserSuccess, registerUserFailure,
  sendConfirmationEmailRequest, sendConfirmationEmailFailure, sendConfirmationEmailSuccess,
  requestConfirmationAccountSuccess, requestConfirmationAccountFailure,
  updateUserRequestSuccess, updateUserRequestFailure,
  resetPasswordSuccess, resetPasswordFailure,
  subscribeUserToPushSuccess, subscribeUserToPushFailure,
  fetchUserSubscriptionToPushSuccess, fetchUserSubscriptionToPushFailure,
  updateUserPictureSuccess, updateUserPictureFailure
} from "../actions/user";
import setAuthorizationHeader from "../data/setAuthorizationHeader";

import api from "../data/api";
import Router from 'next/router';
import _ from "lodash";

export function* requestLoginSaga(action) {
  try {
    const res = yield call(api.user.login, action.data);

    if (!!res.token) {

      localStorage.setItem('ttJWT', res.token)

      setAuthorizationHeader(res.token)

      yield put(userLoggedIn());
      yield put(fetchCurrentUserRequest());
      let url = localStorage.getItem('loginRedirect');
      console.log("requestLoginSaga1!!!!!!!!!!!!!! "+url)
      console.log(url)
      if (!!!url)
        url = "/"
      console.log(url)
      Router.push(url);
      // <Redirect to={url}/>
      console.log("requestLoginSaga2!!!!!!!!!!!!!! "+url)
      //localStorage.setItem('loginRedirect', '/');
    } else{
      throw new Error("Mauvais identifiants.")  
      console.log("requestLoginSaga!!!!!!!!!!!!!! Mauvais identifiants.")
    }
      

  } catch (error) {
    setAuthorizationHeader();
    console.log("requestLoginSaga!!!!!!!!!!!!!! Mauvais identifiants.")
    yield put(requestLoginFailure({ message: "Mauvais identifiants" }));
  }
}

export function* requestLogoutSaga(action) {
  //console.log("function* requestLogoutSaga")
  try {

    setAuthorizationHeader()
    Router.push("/");

  } catch (error) {
    console.error(error)
  } finally {
    yield put(userLoggedOut());
  }
}

export function* requestUserSaga(action) {
  try {
    // console.log('function* requestUserSaga')
    const res = yield call(api.user.fetchUser);
    // console.log(res);
    if (res.status === "success") {

      yield put(fetchCurrentUserSuccess(res.user));

    } else
      throw new Error("no user")

  } catch (error) {
    setAuthorizationHeader()
    yield put(fetchCurrentUserFailure(error));
  }
}

export function* verifyUserSaga(action) {
  try {
    //console.log('function* requestUserSaga')
    const res = yield call(api.user.fetchUser);
    if (res.status === "success") {

      yield put(fetchCurrentUserSuccess(res.user));

    } else
      throw new Error("no user")

  } catch (error) {
    console.error(error)
    setAuthorizationHeader()

    Router.push(`/Login`);
  }
}

///
///{
// type: 'SUBSCRIBE_NEWSLETTER_REQUEST',
// payload: {"email":"gregoire@e-declic.com"}
// }
export function* requestNewsletterSubscribitionSaga(action) {
  try {
    //console.log('function* requestNewsletterSubscribitionSaga')
    const res = yield call(api.user.subscribeToNewsletter, action.payload);

    if (res.data.success === true) {
      yield put(subscribeToNewsletterSuccess(res));
    } else
      console.error(res.data.message);
    if (_.startsWith(res.data.message, 'Unsuccessful: 400 MJ18')) {
      throw new Error("Existe déjà.")
    }
  } catch (err) {
    console.error(err.message)
    yield put(subscribeToNewsletterFailure({ err: err, message: err.message }));
  }
}

export function* requestRegisterSaga(action) {
  try {
    //console.log('function* requestRegisterSaga')
    const res = yield call(api.user.register, action.payload);
    console.log("requestRegisterSaga");
    console.log(res);
    console.log(action);
    if (res.data.status === 'success') {

      yield put(registerUserSuccess(res));
      
      yield put(sendConfirmationEmailRequest(res));
      Router.push(`/VerifyEmail/${action.payload.email}`);

    } else
      throw new Error("L'inscription a échouée. Merci de contacter contact@talentstube.com")

  } catch (err) {
    console.error(err)
    yield put(registerUserFailure(err));
  }
}

export function* sendConfirmationEmailSaga(action) {
  try {
    // console.log('function* sendConfirmationEmailRequest'+action.payload.data)
    const res = yield call(api.user.sendconfirmationEmail, action.payload.data);

    if (res.data.status === 'success') {
      yield put(sendConfirmationEmailSuccess(res));
    } else
      throw new Error("not sent")

  } catch (error) {
    console.error(error)
    yield put(sendConfirmationEmailFailure(error));
  }
}

export function* requestConfirmationAccountSaga(action) {
  try {
    // console.log('function* requestConfirmationAccountSaga'+action.payload)

    const res = yield call(api.user.confirmUserAccount, action.payload);
    if (res.data.status === 'success') {

      yield put(requestConfirmationAccountSuccess(res));

    } else
      throw new Error("not confirmed")

  } catch (err) {
    console.error(err)
    yield put(requestConfirmationAccountFailure(err));
  }
}

export function* requestUpdateUserSaga(action) {
  try {
    console.log('function* requestUpdateUserSaga')
    const res = yield call(api.user.updateUser, action.payload);

    if (res.data.status === 'success') {

      yield put(updateUserRequestSuccess(res));

    } else
      throw new Error(res.message)

  } catch (err) {
    console.error(err)
    yield put(updateUserRequestFailure(err));
  }
}

export function* requestResetPasswordSaga(action) {
  try {
    const res = yield call(api.user.resetPassword, action.payload);
    console.log('function* requestResetPasswordSaga');

    if (!!res.data && res.data.status === "success") {
      yield put(resetPasswordSuccess(res));
    }
    else if (!!res.code && res.code === 400) {
      throw new Error("Vous avez déjà demandé la réinitialisation de votre password.");
    }

  } catch (err) {
    console.error(err.message)
    yield put(resetPasswordFailure({ err: err, message: err.message }));
  }
}

export function* requestSubscribeUserToPushSaga(action) {
  try {
    const res = yield call(api.user.subscribeUserToPush, action.payload);
    console.log('function* requestSubscribeUserToPushSaga');

    if (!!res.data && res.data.success === true) {
      yield put(subscribeUserToPushSuccess(res));
    }
    else {

      throw new Error("Problème système. Veuillez contacter le service client.")
    }
  } catch (err) {
    console.error(err.message)
    yield put(subscribeUserToPushFailure({ err: err, message: err.message }));
  }
}

export function* requestUserSubscriptionToPushSaga(action) {
  try {
    const res = yield call(api.user.fetchUserSubscriptionToPush, action.id);
    console.log('function* requestUserSubscriptionToPushSaga');
    console.log(res);

    if (!!res.data && res.status === 200) {
      yield put(fetchUserSubscriptionToPushSuccess(res.data));
    }
    else {

      throw new Error("Problème système. Veuillez contacter le service client.")
    }
  } catch (err) {
    console.error(err.message)
    yield put(fetchUserSubscriptionToPushFailure({ err: err, message: err.message }));
  }
}

export function* requestUpdateUserRequestSaga(action) {
  try {

    const res = yield call(api.user.uploadPicture, action.payload);
    console.log(res);
    if (!!res.data)
      yield put(updateUserPictureSuccess(res.data));
    else
      yield put(updateUserPictureFailure());

  } catch (err) {
    
    if (_.includes(err, "401") || (!!err.response && err.response.status === 401)) {
      localStorage.setItem('loginRedirect', window.location.pathname)
      console.log("ERREUR 401")
      Router.push("/Login");
    }
    yield put(updateUserPictureFailure(err.response));
  }
}