import {
  call, put, takeLatest, all,
} from 'redux-saga/effects';
import * as Api from '../../../services/api';
import * as types from './constants';

export function* getDefaultWeChatTemplates(params) {
  try {
    const result = yield call(Api.getAllTemplates, { channel: params.channel, queryParams: params.queryParams });
    yield put({ type: types.GET_WECHAT_DEFAULT_TEMPLATES_SUCCESS, data: result.response.unMapped, templateData: result.response.mapped });
  } catch (error) {
    yield put({ type: types.GET_WECHAT_DEFAULT_TEMPLATES_FAILURE, error });
  }
}

export function* createTemplate({ template, callback }) {
  try {
    const result = yield call(Api.createWeChatTemplate, { template });
    if (callback) {
      yield call(callback, result.response);
    }
    // const sidebar = result.response.sidebar;
    yield put({ type: types.CREATE_TEMPLATE_SUCCESS, data: result.response, statusCode: result.status ? result.status.code : '' });
  } catch (error) {
    yield put({ type: types.CREATE_TEMPLATE_FAILURE, error });
  }
}

export function* fetchWeCrmAccounts() {
  try {
    const result = yield call(Api.fetchWeCrmAccounts);
    yield put({
      type: types.GET_WECRM_ACCOUNTS_SUCCESS,
      data: result.response,
    });
  } catch (error) {
    yield put({
      type: types.GET_WECRM_ACCOUNTS_FAILURE,
      data: error,
    });
  }
}

export function* getTemplateDetails(id) {
  try {
    const result = yield call(Api.getTemplateDetails, id);
    // const sidebar = result.response.sidebar;
    yield put({ type: types.GET_TEMPLATE_DETAILS_SUCCESS, data: result.response });
  } catch (error) {
    yield put({ type: types.GET_TEMPLATE_DETAILS_FAILURE, error });
  }
}

function* watchGetDefaultWechatTemplates() {
  yield takeLatest(types.GET_WECHAT_DEFAULT_TEMPLATES_REQUEST, getDefaultWeChatTemplates);
}

function* watchCreateTemplate() {
  yield takeLatest(types.CREATE_TEMPLATE_REQUEST, createTemplate);
}

function* watchFetchWeCrmAccounts() {
  yield takeLatest(types.GET_WECRM_ACCOUNTS_REQUEST, fetchWeCrmAccounts);
}

function* watchGetTemplateDetails() {
  yield takeLatest(types.GET_TEMPLATE_DETAILS_REQUEST, getTemplateDetails);
}

// All sagas to be loaded
export default [
  watchGetDefaultWechatTemplates,
  watchCreateTemplate,
  watchFetchWeCrmAccounts,
  watchGetTemplateDetails,
];

export function* v2WechatMapTemplatesSagas() {
  yield all([
    watchGetDefaultWechatTemplates(),
    watchCreateTemplate(),
    watchFetchWeCrmAccounts(),
    watchGetTemplateDetails(),
  ]);
}
