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

// Individual exports for testing
export function* createTemplate(template) {
  let errorMsg;
  try {
    
    const result = yield call(Api.createMobilePushTemplate, template);
    if (result.message) {
      errorMsg = result.message;
      if(result.status.code>=400){
        throw errorMsg;
      }
    }
    if (template.callback) {
      yield call(template.callback, result.response);
    }
    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* uploadAsset(file, assetType, fileParams) {
  try {
    const result = yield call(Api.uploadFile, file, assetType, fileParams);
    yield put({ type: types.UPLOAD_ASSET_SUCCESS, data: result.response.asset, statusCode: result.status ? result.status.code : '' });
  } catch (error) {
    yield put({ type: types.UPLOAD_ASSET_FAILURE, error });
  }
}
export function* getIosCtas(licenseCode) {
  try {
    const result = yield call(Api.getIosCtas, licenseCode);
    yield put({ type: types.GET_IOS_CTAS_SUCCESS, data: result.response.metaEntities.data, statusCode: result.status ? result.status.code : '' });
  } catch (error) {
    yield put({ type: types.GET_IOS_CTAS_FAILURE, error });
  }
}

function* watchCreateTemplate() {
  
  yield takeLatest(types.CREATE_TEMPLATE_REQUEST, createTemplate);
  
  
}
function* watchUploadAsset() {
  yield takeLatest(types.UPLOAD_ASSET_REQUEST, uploadAsset);
  
  
}
function* watchGetIosCtas() {
  yield takeLatest(types.GET_IOS_CTAS, getIosCtas);
  
  
}
// All sagas to be loaded
export default [
  watchCreateTemplate,
  watchUploadAsset,
  watchGetIosCtas,
];

export function* v2MobilePushCreateSagas() {
  yield all([
    watchCreateTemplate(),
  ]);
}

export function* v2MobilePushWatchDuplicateTemplateSaga() {
  yield all([
    watchGetIosCtas(),
    watchUploadAsset(),
  ]);
}