/*
 *
 * SmsTrai reducer
 *
 */

import { fromJS } from 'immutable';
import {
  CREATE_TRAI_SMS_TEMPLATE_REQUEST,
  CREATE_TRAI_SMS_TEMPLATE_SUCCESS,
  CREATE_TRAI_SMS_TEMPLATE_FAILURE,
  CLEAR_TRAI_SMS_TEMPLATE_CREATE_RESPONSE_REQUEST,
  CHECK_TRAI_SMS_DUPLICATE_TEMPLATE_NAME_REQUEST,
  CHECK_TRAI_SMS_DUPLICATE_TEMPLATE_NAME_SUCCESS,
  CHECK_TRAI_SMS_DUPLICATE_TEMPLATE_NAME_FAILURE,
  REQUEST,
  SUCCESS,
  FAILURE,
} from './constants';

const initialState = fromJS({
  createTemplateInProgress: false,
  duplicateDetailsStatus: '',
  duplicateDetails: {},
  duplicateDetailsError: '',
});

function smsTraiReducer(state = initialState, action) {
  switch (action.type) {
    case CREATE_TRAI_SMS_TEMPLATE_REQUEST:
      return state
      .set('createTemplateInProgress', true)
      .set('createTemplateError', false)
      .set('createTemplateErrorMessage', fromJS(""));
    case CREATE_TRAI_SMS_TEMPLATE_SUCCESS:
      return state.set('createTemplateInProgress', false)
      .set('response', action.data)
      .set('createTemplateError', (action.statusCode !== undefined && action.statusCode > 300))
      .set('createTemplateErrorMessage', fromJS(action.errorMsg));
    case CREATE_TRAI_SMS_TEMPLATE_FAILURE:
      return state
      .set('createTemplateInProgress', false)
      .set('createTemplateError', true)
      .set('createTemplateErrorMessage', fromJS(action.errorMsg));
    case CLEAR_TRAI_SMS_TEMPLATE_CREATE_RESPONSE_REQUEST:
      return state.set('response', {});
    case CHECK_TRAI_SMS_DUPLICATE_TEMPLATE_NAME_REQUEST:
      return state
        .set('duplicateDetailsStatus', REQUEST)
        .set('duplicateDetails', {})
        .set('duplicateDetailsError', '');
    case CHECK_TRAI_SMS_DUPLICATE_TEMPLATE_NAME_SUCCESS:
      return state
        .set('duplicateDetailsStatus', SUCCESS)
        .set('duplicateDetails', action.data)
        .set('duplicateDetailsError', '');
    case CHECK_TRAI_SMS_DUPLICATE_TEMPLATE_NAME_FAILURE:
      return state
        .set('duplicateDetailsStatus', FAILURE)
        .set('duplicateDetails', {})
        .set('duplicateDetailsError', action.error);
    default:
      return state;
  }
}

export default smsTraiReducer;
