import UserActionTypes from "./user.types";

const INITIAL_STATE = {
  currentUser: {
    authorized: null
    //language: "en-US"
  },
  bodyshop: null,
  targets: null,
  fingerprint: null,
  error: null,
  conflict: false,
  passwordreset: {
    email: null,
    error: null,
    success: false
  },
  loginLoading: false,
  notifications: null,
  darkMode: false
};

const userReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case UserActionTypes.SET_TARGETS:
      return { ...state, targets: action.payload };
    case UserActionTypes.SET_NOTIFICATIONS:
      return { ...state, notifications: action.payload };
    case UserActionTypes.SET_SHOP_DETAILS:
      return { ...state, bodyshop: action.payload };
    case UserActionTypes.SET_LOCAL_FINGERPRINT:
      return { ...state, fingerprint: action.payload };

    case UserActionTypes.VALIDATE_PASSWORD_RESET_START:
    case UserActionTypes.SEND_PASSWORD_RESET_EMAIL_START:
      return {
        ...state,
        passwordreset: {
          email: action.payload,
          error: null,
          success: false
        }
      };
    case UserActionTypes.VALIDATE_PASSWORD_RESET_FAILURE:
    case UserActionTypes.SEND_PASSWORD_RESET_EMAIL_FAILURE:
      return { ...state, passwordreset: { error: action.payload } };
    case UserActionTypes.VALIDATE_PASSWORD_RESET_SUCCESS:
    case UserActionTypes.SEND_PASSWORD_RESET_EMAIL_SUCCESS:
      return {
        ...state,
        passwordreset: { ...state.passwordreset, success: true }
      };
    case UserActionTypes.SIGN_IN_SUCCESS:
      return {
        ...state,
        currentUser: action.payload,
        loginLoading: false,
        error: null
      };
    case UserActionTypes.SIGN_OUT_SUCCESS:
      return {
        ...state,
        currentUser: { authorized: false },
        error: null
      };
    case UserActionTypes.UNAUTHORIZED_USER:
      return {
        ...state,
        error: null,
        currentUser: { authorized: false }
      };
    case UserActionTypes.SET_USER_LANGUAGE:
      return {
        ...state,
        language: action.payload
      };
    case UserActionTypes.UPDATE_USER_DETAILS_SUCCESS:
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          ...action.payload //Spread current user details in.
        }
      };
    case UserActionTypes.TOGGLE_DARK_MODE:
      return {
        ...state,
        darkMode: !state.darkMode
      };
    case UserActionTypes.SIGN_IN_FAILURE:
    case UserActionTypes.SIGN_OUT_FAILURE:
    case UserActionTypes.EMAIL_SIGN_UP_FAILURE:
      return {
        ...state,
        error: action.payload,
        loginLoading: false
      };
    case UserActionTypes.EMAIL_SIGN_IN_START:
      return { ...state, loginLoading: true };
    default:
      return state;
  }
};

export default userReducer;
