import {
  call, put, takeLatest, all,
} from 'redux-saga/effects';
import orderBy from 'lodash/orderBy';
import moment from 'moment';
import * as Api from '../../../../services/api';
import * as types from './constants';
// import testschema from './testschema';
// Individual exports for testing
export function* defaultSaga() {
  // See example in v2Containers/HomePage/sagas.js
}
export function* uploadAsset({file, assetType, fileParams, mode, wechatParams, contentId, uploadId}) {
  try {
    const params = {
      file, assetType, fileParams, mode, wechatParams,
    };
    const result = yield call(Api.uploadFile, params);
    yield put({ type: types.UPLOAD_ASSET_SUCCESS, data: result.response.asset, statusCode: result.status ? result.status.code : '', contentId, uploadId});
  } catch (error) {
    yield put({ type: types.UPLOAD_ASSET_FAILURE, error });
  }
}
export function* saveTemplate({template, callback}) {
  try {
    let errorMsg;
    const result = yield call(Api.createWeChatTemplate, {template});
    if (!result.success || result.status.code === 500) {
      errorMsg = result.message;
    }
    if (callback && !errorMsg) {
      yield call(callback, result.response);
    }
    yield put({ type: types.SAVE_TEMPLATE_SUCCESS, data: result.response, statusCode: result.status ? result.status.code : '', errorMsg});
  } catch (error) {
    yield put({ type: types.SAVE_TEMPLATE_FAILURE, error });
  }
}

export function* getAllTemplates(action) {
  try {
    const result = yield call(Api.getAllTemplates, action);
    const channelTemplates = {
      templates: result.response.richmedia,
    };
    if (
      action.channel === 'wechat' &&
      action.queryParams &&
      action.queryParams.sortBy
      ) {
      if (action.queryParams.sortBy.toLocaleLowerCase() === ("Most Recent").toLocaleLowerCase()) {
        channelTemplates.templates = orderBy(channelTemplates.templates, (template) => moment(template.updatedAt), ['desc']);
        // channelTemplates.templates.sort((a, b) => {
        //   const dateA = new Date(a.updatedAt);
        //   const dateB = new Date(b.updatedAt);
        //   return dateB - dateA;
        // });
      } else if (action.queryParams.sortBy.toLocaleLowerCase() === ("Alphabetically").toLocaleLowerCase()) {
        channelTemplates.templates.sort((a, b) => b.name - a.name);
      }
    }
    yield put({
      type: types.GET_ALL_TEMPLATES_SUCCESS,
      data: channelTemplates,
      isReset: action.queryParams.page === 1,
    });
  } catch (error) {
    yield put({
      type: types.GET_ALL_TEMPLATES_FAILURE,
      error,
    });
  }
}

function* watchGetAllTemplates() {
  yield takeLatest(types.GET_ALL_TEMPLATES_REQUEST, getAllTemplates);
}

function* watchUploadAsset() {
  yield takeLatest(types.UPLOAD_ASSET_REQUEST, uploadAsset);
}
function* watchSaveTemplate() {
  yield takeLatest(types.SAVE_TEMPLATE_REQUEST, saveTemplate);
}
// All sagas to be loaded
export default [
  defaultSaga,
  watchUploadAsset,
  watchSaveTemplate,
  watchGetAllTemplates,
];

export function* v2WechatRichmediaTemplatesCreateSagas() {
  yield all([
    watchUploadAsset(),
    watchSaveTemplate(),
    watchGetAllTemplates(),
  ]);
}