import { ActionType, AuthActions, UserActions } from '../actions';
import { User } from '../models';

const INITIAL_STATE: User = {
  body: null,
  role: null,
  firstLogin: false,
};

export function userReducer(state = INITIAL_STATE, action: ActionType): User {
  switch (action.type) {
    case AuthActions.ActionKey.FIRST_LOGIN:
      return {
        ...state,
        firstLogin: true,
      };
    case AuthActions.ActionKey.LOGIN_SUCCESS:
      return {
        ...state,
        body: action.user,
        role: action.userRole as any,
      };
    case UserActions.ActionKey.USER_LOCATION_UPDATE_REQUEST:
      return {
        ...state,
        body: {
          ...state.body as any,
          location: action.location,
        },
      };
    case UserActions.ActionKey.USER_PROFILE_EDIT_SUCCESS:
      return {
        ...state,
        body: {
          ...state.body as any,
          ...action.user,
        },
        firstLogin: false,
      };
    case UserActions.ActionKey.USER_PHOTO_UPLOAD_SUCCESS:
      return {
        ...state,
        body: {
          ...state.body as any,
          avatar: action.downloadUrl,
        },
      };
    case AuthActions.ActionKey.LOGIN_FAIL:
    case AuthActions.ActionKey.LOGOUT_REQUESTED:
      return INITIAL_STATE;
    default:
      return state;
  }
}
