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


export function* createTemplate(template) {
  let errorMsg = "";
  try {
    
    const result = yield call(Api.createEbillTemplate, template);
    if ((result.message && typeof result.message === 'string') || result.status.code === 500) {
      errorMsg = result.message;
    }
    yield put({ type: types.CREATE_TEMPLATE_SUCCESS, data: result.response, statusCode: result.status ? result.status.code : '', errorMsg });
  } catch (error) {
    yield put({ type: types.CREATE_TEMPLATE_FAILURE, error, errorMsg });
  }
}

export function* getTemplateDetails(id, channel) {
  try {
    
    const result = yield call(Api.getTemplateDetails, id, channel);
    // 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 });
  }
}

export function* getCmsData({cmsType, projectId}) {
  try {
    const result = yield call(Api.getCmsData, cmsType, projectId);
    
    yield put({ type: types.GET_CMS_EDITOR_DATA_SUCCESS, data: decodeURIComponent(result.data.response.cmsData.htmlContent) });
  } catch (error) {
    yield put({ type: types.GET_CMS_EDITOR_DATA_FAILURE, error });
  }
}

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

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

function* watchGetCmsData() {
  yield takeLatest(types.GET_CMS_EDITOR_DATA_REQUEST, getCmsData);
}

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

export function* v2EbillSagas() {
  yield all([
    watchCreateTemplate(),
    watchGetTemplateDetails(),
    watchGetCmsData(),
  ]);
}