import moment from 'moment';
import {
  LOGGED_IN,
  LOGIN_ERROR,
  LOG_IN,
  LOG_OUT,
} from '../constants/actionTypes';

const initialState = {
  username: null,
  isSSO: false,
  sessionId: null,
  expirationTime: null,
  fullName: null,
  name: null,
  isAdministrator: false,
  isAuthenticating: false,
  isSessionExpired: false,
  error: null,
};

const user = (state = initialState, action) => {
  switch (action.type) {
    case LOG_IN: {
      state = {
        ...initialState,
        username: action.username,
        isSSO: action.username === null,
        isAuthenticating: true,
      };
      break;
    }
    case LOGGED_IN: {
      state = {
        ...initialState,
        username: state.username,
        isSSO: state.isSSO,
        sessionId: action.sessionId,
        expirationTime: moment()
          .add(action.lifeTimeMinutes, 'minutes')
          .format(),
        fullName: action.fullName,
        name: action.name,
        isAdministrator: action.isAdministrator,
      };
      break;
    }
    case LOG_OUT: {
      state = { ...initialState, isSessionExpired: action.expired };
      break;
    }
    case LOGIN_ERROR: {
      state = { ...initialState, error: action.error };
      break;
    }
    default:
      break;
  }
  return state;
};

export default user;
