/*
 *
 * WeChat reducer
 *
 */

import { fromJS } from 'immutable';
import * as types from './constants';

const initialState = fromJS({
  weChatDefaultTemplate: fromJS({}),
  fetchingDefaultTemplates: false,
  errorFetchingDefaultTempalte: false,
});

function weChatReducer(state = initialState, action) {
  switch (action.type) {
    case types.GET_WECHAT_DEFAULT_TEMPLATES_REQUEST:
      return state
        .set('fetchingDefaultTemplates', true)
        .set('weChatDefaultTemplate', fromJS({}))
        .set('weChatTemplates', fromJS({}))
        .set('errorFetchingDefaultTempalte', false);
    case types.GET_WECHAT_DEFAULT_TEMPLATES_SUCCESS:
      return state
        .set('fetchingDefaultTemplates', false)
        .set('weChatDefaultTemplate', fromJS(action.data))
        .set('weChatTemplates', fromJS(action.templateData));
    case types.GET_WECHAT_DEFAULT_TEMPLATES_FAILURE:
      return state
        .set('fetchingDefaultTemplates', false)
        .set('errorFetchingDefaultTempalte', true);
    case types.CREATE_TEMPLATE_REQUEST:
      return state
        .set('createTemplateInProgress', true)
        .set('createTemplateError', false);
    case types.CREATE_TEMPLATE_SUCCESS:
      return state.set('createTemplateInProgress', false)
        .set('createResponse', action.data)
        .set('createTemplateError', (action.statusCode !== undefined && action.statusCode > 300));
    case types.CREATE_TEMPLATE_FAILURE:
      return state
        .set('createTemplateInProgress', false)
        .set('createTemplateError', true);
    case types.CLEAR_CREATE_RESPONSE_REQUEST:
      return state.set('createResponse', {});
    case types.GET_WECRM_ACCOUNTS_REQUEST:
      return state
        .set('fetchingWeCrmAccounts', true)
        .set('weCrmAccountFetchingError', false);
    case types.GET_WECRM_ACCOUNTS_SUCCESS:
      return state
        .set('fetchingWeCrmAccounts', false)
        .set('weCrmAccounts', fromJS(action.data));
    case types.GET_WECRM_ACCOUNTS_FAILURE:
      return state
        .set('fetchingWeCrmAccounts', false)
        .set('weCrmAccountFetchingError', true);
    case types.GET_TEMPLATE_DETAILS_REQUEST:
      return state.set('getTemplateDetailsInProgress', true);
    case types.GET_TEMPLATE_DETAILS_SUCCESS:
      return state.set('getTemplateDetailsInProgress', false)
        .set('templateDetails', action.data);
    case types.GET_TEMPLATE_DETAILS_FAILURE:
      return state.set('getTemplateDetailsInProgress', false);
    case types.SET_WECHAT_ACCOUNT:
      return state
        .set('selectedWeChatAccount', fromJS(action.weChatAccount));
    default:
      return state;
  }
}

export default weChatReducer;
