'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.makeSearchQuery = makeSearchQuery;
exports.fetchYoutubePlaylist = fetchYoutubePlaylist;
exports.fetchTwitterTimeline = fetchTwitterTimeline;
exports.fetchLatestPosts = fetchLatestPosts;
exports.fetchEvent = fetchEvent;
exports.fetchTopics = fetchTopics;
exports.fetchTopic = fetchTopic;
exports.fetchImages = fetchImages;
exports.fetchAudios = fetchAudios;
exports.fetchIndexArticles = fetchIndexArticles;
exports.fetchRelatedArticlesIfNeeded = fetchRelatedArticlesIfNeeded;
exports.fetchArticlesByUuidIfNeeded = fetchArticlesByUuidIfNeeded;
exports.fetchFeatureArticles = fetchFeatureArticles;

var _index = require('../constants/index');

var _customError = require('../lib/custom-error');

var _normalizr = require('normalizr');

var _index2 = require('../schemas/index');

var _humps = require('humps');

var _index3 = require('../utils/index');

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _actionTypes = require('../constants/action-types');

var types = _interopRequireWildcard(_actionTypes);

var _isomorphicFetch = require('isomorphic-fetch');

var _isomorphicFetch2 = _interopRequireDefault(_isomorphicFetch);

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function requestArticlesByUuid(id, url) {
  return {
    type: types.FETCH_ARTICLES_BY_GROUP_UUID_REQUEST,
    id: id,
    url: url
  };
}

function failToReceiveArticlesByUuid(id, error) {
  return {
    type: types.FETCH_ARTICLES_BY_GROUP_UUID_FAILURE,
    id: id,
    error: error,
    failedAt: Date.now()
  };
}

function receiveArticlesByUuid(response, id) {
  return {
    type: types.FETCH_ARTICLES_BY_GROUP_UUID_SUCCESS,
    id: id,
    response: response,
    receivedAt: Date.now()
  };
}

function requestRelatedArticles(id, relatedIds, url) {
  return {
    type: types.FETCH_RELATED_ARTICLES_REQUEST,
    id: id,
    relatedIds: relatedIds,
    url: url
  };
}

function failToReceiveRelatedArticles(id, relatedIds, error) {
  return {
    type: types.FETCH_RELATED_ARTICLES_FAILURE,
    id: id,
    relatedIds: relatedIds,
    error: error,
    failedAt: Date.now()
  };
}

function receiveRelatedArticles(response, id, relatedIds) {
  return {
    type: types.FETCH_RELATED_ARTICLES_SUCCESS,
    id: id,
    relatedIds: relatedIds,
    response: response,
    receivedAt: Date.now()
  };
}

function requestFeatureArticles(url) {
  return {
    type: types.FETCH_FEATURE_ARTICLES_REQUEST,
    url: url
  };
}

function failToReceiveFeatureArticles(error) {
  return {
    type: types.FETCH_FEATURE_ARTICLES_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function receiveFeaturedArticles(response) {
  return {
    type: types.FETCH_FEATURE_ARTICLES_SUCCESS,
    response: response,
    receivedAt: Date.now()
  };
}

function requestIndexArticles(url) {
  return {
    type: types.FETCH_INDEX_ARTICLES_REQUEST,
    url: url
  };
}

function requestEvent(url) {
  return {
    type: types.FETCH_EVENT_REQUEST,
    url: url
  };
}

function requestTopics(url) {
  return {
    type: types.FETCH_TOPICS_REQUEST,
    url: url
  };
}

function requestTopic(url) {
  return {
    type: types.FETCH_TOPIC_REQUEST,
    url: url
  };
}

function requestImages(url) {
  return {
    type: types.FETCH_IMAGES_REQUEST,
    url: url
  };
}

function requestAudios(url) {
  return {
    type: types.FETCH_IMAGES_REQUEST,
    url: url
  };
}

function failToReceiveIndexArticles(error) {
  return {
    type: types.FETCH_INDEX_ARTICLES_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function failToReceiveLatestPosts(error) {
  return {
    type: types.FETCH_LATEST_POSTS_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function failToReceiveEvent(error) {
  return {
    type: types.FETCH_EVENT_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function failToReceiveTopics(error) {
  return {
    type: types.FETCH_TOPICS_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function failToReceiveTopic(error) {
  return {
    type: types.FETCH_TOPIC_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function failToReceiveImages(error) {
  return {
    type: types.FETCH_IMAGES_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function failToReceiveAudios(error) {
  return {
    type: types.FETCH_IMAGES_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function receiveSectionFeatured(response) {
  return {
    type: types.FETCH_SECTIONS_FEATURED_SUCCESS,
    response: response,
    receivedAt: Date.now()
  };
}

function failToReceiveSectionFeatured(error) {
  return {
    type: types.FETCH_SECTIONS_FEATURED_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function receiveChoices(response) {
  return {
    type: types.FETCH_CHOICES_SUCCESS,
    response: response,
    receivedAt: Date.now()
  };
}

function failToReceiveChoices(error) {
  return {
    type: types.FETCH_CHOICES_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function receiveLatestPosts(response, meta, links) {
  return {
    type: types.FETCH_LATEST_POSTS_SUCCESS,
    response: response,
    meta: meta,
    links: links,
    receivedAt: Date.now()
  };
}

function receiveEvent(response, meta, links) {
  return {
    type: types.FETCH_EVENT_SUCCESS,
    response: response,
    meta: meta,
    links: links,
    receivedAt: Date.now()
  };
}

function receiveTopics(response, meta, links) {
  return {
    type: types.FETCH_TOPICS_SUCCESS,
    response: response,
    meta: meta,
    links: links,
    receivedAt: Date.now()
  };
}

function receiveTopic(response) {
  return {
    type: types.FETCH_TOPIC_SUCCESS,
    response: response,
    receivedAt: Date.now()
  };
}

function receiveImages(response) {
  return {
    type: types.FETCH_IMAGES_SUCCESS,
    response: response,
    receivedAt: Date.now()
  };
}

function receiveAudios(response, meta, links) {
  return {
    type: types.FETCH_AUDIOS_SUCCESS,
    response: response,
    meta: meta,
    links: links,
    receivedAt: Date.now()
  };
}

function receivedSectionList(response) {
  return {
    type: types.FETCH_SECTION_LIST_SUCCESS,
    response: response,
    receivedAt: Date.now()
  };
}

function failToReceiveSectionList(error) {
  return {
    type: types.FETCH_SECTION_LIST_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function requestSearchResult(url) {
  return {
    type: types.FETCH_SEARCH_RESULT_REQUEST,
    url: url,
    requestAt: Date.now()
  };
}

function receiveSearchResult(response) {
  return {
    type: types.FETCH_SEARCH_RESULT_SUCCESS,
    response: response,
    receivedAt: Date.now()
  };
}

function failToReceiveSearchResult(error) {
  return {
    type: types.FETCH_SEARCH_RESULT_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function requestYoutubePlaylist(url) {
  return {
    type: types.FETCH_YOUTUBE_PLAYLIST_REQUEST,
    url: url,
    requestAt: Date.now()
  };
}

function receiveYoutubePlaylist(response) {
  return {
    type: types.FETCH_YOUTUBE_PLAYLIST_SUCCESS,
    response: response,
    receivedAt: Date.now()
  };
}

function failToReceiveYoutubePlaylist(error) {
  return {
    type: types.FETCH_YOUTUBE_PLAYLIST_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function requestTwitterTimeline(url) {
  return {
    type: types.FETCH_TWITTER_TIMELINE_REQUEST,
    url: url,
    requestAt: Date.now()
  };
}

function receiveTwitterTimeline(response) {
  return {
    type: types.FETCH_TWITTER_TIMELINE_SUCCESS,
    response: response,
    receivedAt: Date.now()
  };
}

function failToReceiveTwitterTimeline(error) {
  return {
    type: types.FETCH_TWITTER_TIMELINE_FAILURE,
    error: error,
    failedAt: Date.now()
  };
}

function _buildQuery() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

  var query = {};
  var whitelist = ['where', 'embedded', 'max_results', 'page', 'sort'];
  _lodash2.default.forEach(whitelist, function (ele) {
    if (params.hasOwnProperty(ele)) {
      if (ele === 'where' || ele === 'embedded') {
        query[ele] = JSON.stringify(params[ele]);
      } else {
        query[ele] = params[ele];
      }
    }
  });
  query = _qs2.default.stringify(query);
  return query;
}

function _buildPostQueryUrl() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

  var query = _buildQuery(params);
  return (0, _index3.formatUrl)('posts?' + query);
}

function _buildMetaQueryUrl() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

  var query = _buildQuery(params);
  return (0, _index3.formatUrl)('meta?' + query);
}

function _buildTopicQueryUrl() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  var slug = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];

  var query = _buildQuery(params);
  return (0, _index3.formatUrl)('topics/' + slug + '?' + query);
}

function _buildEventQueryUrl() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

  var query = _buildQuery(params);
  return (0, _index3.formatUrl)('event?' + query);
}

function _buildImageQueryUrl() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

  var query = _buildQuery(params);
  return (0, _index3.formatUrl)('images?' + query);
}

function _buildAudioQueryUrl() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

  var query = _buildQuery(params);
  return (0, _index3.formatUrl)('audios?' + query);
}

function _buildUrl() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  var target = arguments[1];

  params = params || {};
  params.sort = params.sort || '-publishedDate';
  if (target === 'meta') {
    return _buildMetaQueryUrl(params);
  }
  return _buildPostQueryUrl(params);
}

function _setupWhereInParam(key, value) {
  var params = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];

  params = params || {};
  value = Array.isArray(value) ? value : [value];
  var where = {};
  if (value.length > 0) {
    _lodash2.default.merge(where, params.where, _defineProperty({}, key, {
      '$in': value
    }));
  }
  params.where = where;
  return params;
}

function _fetchArticles(url) {
  return (0, _isomorphicFetch2.default)(url).then(function (response) {
    var status = response.status;
    if (status === 404) {
      throw new _customError.NotFoundError('Resource are not found by url: ', url);
    } else if (status >= 400) {
      throw new _customError.InternalServerError('Bad response from API, response: ' + JSON.stringify(response));
    }
    return response.json();
  });
}

function makeSearchQuery(keyword) {
  var url = (0, _index3.formatUrl)('search?query=' + keyword);
  return function (dispatch) {
    dispatch(requestSearchResult(url));
    return _fetchArticles(url).then(function (response) {
      dispatch(receiveSearchResult(response));
    }, function (error) {
      dispatch(failToReceiveSearchResult(error));
    });
  };
}

function fetchYoutubePlaylist() {
  var limit = arguments.length <= 0 || arguments[0] === undefined ? 10 : arguments[0];
  var pageToken = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];

  var url = (0, _index3.formatUrl)('playlist?maxResults=' + limit + '&pageToken=' + pageToken);
  return function (dispatch) {
    dispatch(requestYoutubePlaylist(url));
    return _fetchArticles(url).then(function (response) {
      dispatch(receiveYoutubePlaylist(response));
    }, function (error) {
      dispatch(failToReceiveYoutubePlaylist(error));
    });
  };
}

function fetchTwitterTimeline() {
  var screen_name = arguments.length <= 0 || arguments[0] === undefined ? 'MirrorWatchTW' : arguments[0];
  var count = arguments.length <= 1 || arguments[1] === undefined ? 10 : arguments[1];

  var url = (0, _index3.formatUrl)('twitter?screen_name=' + screen_name + '&count=' + count);
  return function (dispatch) {
    dispatch(requestTwitterTimeline(url));
    return _fetchArticles(url).then(function (response) {
      dispatch(receiveTwitterTimeline(response));
    }, function (error) {
      dispatch(failToReceiveTwitterTimeline(error));
    });
  };
}

function fetchLatestPosts() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

  var url = _buildPostQueryUrl(params);
  return function (dispatch) {
    dispatch(requestIndexArticles('Request Latest Post: ' + url));
    return _fetchArticles(url).then(function (response) {
      var meta = response._meta;
      var links = response._links;
      var camelizedJson = (0, _humps.camelizeKeys)(response);
      response = (0, _normalizr.normalize)(camelizedJson.items, (0, _normalizr.arrayOf)(_index2.article));
      dispatch(receiveLatestPosts(response, meta, links));
    }, function (error) {
      return dispatch(failToReceiveLatestPosts(error));
    });
  };
}

function fetchEvent() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

  var url = _buildEventQueryUrl(params);
  return function (dispatch) {
    dispatch(requestEvent('Request Event: ' + url));
    return _fetchArticles(url).then(function (response) {
      var meta = response._meta;
      var links = response._links;
      var camelizedJson = (0, _humps.camelizeKeys)(response);
      dispatch(receiveEvent(camelizedJson.items, meta, links));
    }, function (error) {
      return dispatch(failToReceiveEvent(error));
    });
  };
}

function fetchTopics() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

  var url = _buildTopicQueryUrl(params);
  return function (dispatch) {
    dispatch(requestTopics('Request Topics: ' + url));
    return _fetchArticles(url).then(function (response) {
      var meta = response._meta;
      var links = response._links;
      var camelizedJson = (0, _humps.camelizeKeys)(response);
      dispatch(receiveTopics(camelizedJson.items, meta, links));
    }, function (error) {
      return dispatch(failToReceiveTopics(error));
    });
  };
}

function fetchTopic(slug) {
  var url = _buildTopicQueryUrl({}, slug);
  return function (dispatch) {
    dispatch(requestTopic('Request Topic: ' + url));
    return _fetchArticles(url).then(function (response) {
      var camelizedJson = (0, _humps.camelizeKeys)(response);
      dispatch(receiveTopic(camelizedJson));
    }, function (error) {
      return dispatch(failToReceiveTopic(error));
    });
  };
}

function fetchImages() {
  var type = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];
  var uuid = arguments[1];
  var params = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];

  switch (type) {
    case _index.SECTION:
      params = _setupWhereInParam('sections', [uuid], params);
      break;
    case _index.CATEGORY:
      params = _setupWhereInParam('categories', [uuid], params);
      break;
    case _index.TAG:
      params = _setupWhereInParam('tags', [uuid], params);
      break;
    case _index.TOPIC:
      params = _setupWhereInParam('topics', [uuid], params);
      break;
    default:
      return Promise.resolve();
  }
  var url = _buildImageQueryUrl(params);
  return function (dispatch) {
    dispatch(requestImages('Request Images: ' + url));
    return _fetchArticles(url).then(function (response) {
      var camelizedJson = (0, _humps.camelizeKeys)(response);
      dispatch(receiveImages(camelizedJson));
    }, function (error) {
      return dispatch(failToReceiveImages(error));
    });
  };
}

function fetchAudios() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

  var url = _buildAudioQueryUrl(params);
  return function (dispatch) {
    dispatch(requestAudios('Request Audios: ' + url));
    return _fetchArticles(url).then(function (response) {
      var meta = response._meta;
      var links = response._links;
      var camelizedJson = (0, _humps.camelizeKeys)(response);
      dispatch(receiveAudios(camelizedJson.items, meta, links));
    }, function (error) {
      return dispatch(failToReceiveAudios(error));
    });
  };
}

function fetchIndexArticles() {
  var endpoints = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];

  var mapped = _lodash2.default.map(endpoints, function (n) {
    return 'endpoint=' + n;
  });
  var combo_params = mapped.join('&');
  var url = (0, _index3.formatUrl)('combo?' + combo_params);
  return function (dispatch) {
    dispatch(requestIndexArticles(url));
    return _fetchArticles(url).then(function (response) {
      var resp_data = response['_endpoints'];
      for (var e in resp_data) {
        if (e == 'posts') {
          if (resp_data.hasOwnProperty(e)) {
            var meta = resp_data[e]['_meta'];
            var links = resp_data[e]['_links'];
            var camelizedJson = (0, _humps.camelizeKeys)(resp_data[e]);
            resp_data[e] = (0, _normalizr.normalize)(camelizedJson.items, (0, _normalizr.arrayOf)(_index2.article));
            dispatch(receiveLatestPosts(resp_data['posts'], meta, links));
          } else {
            dispatch(failToReceiveLatestPosts('There is no such key in indexArticles'));
          }
        } else if (e == 'choices') {
          if (resp_data.hasOwnProperty(e)) {
            var _camelizedJson = (0, _humps.camelizeKeys)(resp_data[e]);
            resp_data[e] = (0, _normalizr.normalize)(_camelizedJson.items, (0, _normalizr.arrayOf)(_index2.article));
            dispatch(receiveChoices(resp_data['choices']));
          } else {
            dispatch(failToReceiveChoices('There is no such key in indexArticles'));
          }
        } else if (e == 'sectionfeatured') {
          if (resp_data.hasOwnProperty(e)) {
            var _camelizedJson2 = (0, _humps.camelizeKeys)(resp_data[e]);
            resp_data[e] = {};
            for (var section in _camelizedJson2.items) {
              if (_camelizedJson2.items[section] != undefined) {
                resp_data[e][section] = (0, _normalizr.normalize)(_camelizedJson2.items[section], (0, _normalizr.arrayOf)(_index2.article));
              }
            }
            dispatch(receiveSectionFeatured(resp_data['sectionfeatured']));
          } else {
            dispatch(failToReceiveSectionFeatured('There is no such key in indexArticles'));
          }
        } else if (e == 'sections') {
          if (resp_data.hasOwnProperty(e)) {
            var _camelizedJson3 = (0, _humps.camelizeKeys)(resp_data[e]);
            var dispatch_data = {};
            dispatch_data['sections'] = _camelizedJson3['items'];
            dispatch_data['categories'] = {};
            for (var c in _camelizedJson3['items']) {
              for (var i in _camelizedJson3['items'][c]['categories']) {
                if (_lodash2.default.get(_camelizedJson3, ['items', c, 'categories', i, 'name'], undefined)) dispatch_data['categories'][_lodash2.default.get(_camelizedJson3, ['items', c, 'categories', i, 'name'], undefined)] = _camelizedJson3['items'][c]['categories'][i];
              }
            }
            dispatch(receivedSectionList(dispatch_data));
          } else {
            dispatch(failToReceiveSectionList('Fetching section list failed'));
          }
        }
      }
    }, function (error) {
      return dispatch(failToReceiveIndexArticles(error));
    });
  };
}

/* Fetch related articles' meta of one certain article
 * properties of meta: subtitle, name, heroImage, title, topics, publishedDate, slug, links, created and id
 * @param {string} articleId
 * @param {string[]} relatedIds - related article ids
 * @param {object} params - params for composing query param of api
 * @param {string} [params.sort=-publishedDate] -the way returned articles are sorted by
 * @param {object} params.where - where query param
 * @param {object} params.embedded - embedded query param
 * @param {boolean} isOnlyMeta - if true, only get metadata of articles. Otherwise, get full articles.
 */
function fetchRelatedArticlesIfNeeded(articleId, relatedIds) {
  var params = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  var isOnlyMeta = arguments.length <= 3 || arguments[3] === undefined ? true : arguments[3];

  return function (dispatch, getState) {
    if (!articleId) {
      return Promise.resolve();
    }
    var articles = _lodash2.default.get(getState(), ['entities', 'articles'], {});
    var idsToFetch = [];

    _lodash2.default.forEach(relatedIds, function (id) {
      if (!_lodash2.default.has(articles, id)) {
        idsToFetch.push(id);
      }
    });

    if (_lodash2.default.get(idsToFetch, 'length', 0) === 0) {
      return Promise.resolve();
    }

    params = _setupWhereInParam('_id', idsToFetch, params);

    if (!isOnlyMeta) {
      // add default embedded
      params.embedded = params.embedded ? params.embedded : (0, _index3.getArticleEmbeddedQuery)();
    }

    var url = _buildUrl(params, isOnlyMeta ? 'meta' : 'article');
    dispatch(requestRelatedArticles(articleId, idsToFetch, url));
    return _fetchArticles(url).then(function (response) {
      var camelizedJson = (0, _humps.camelizeKeys)(response);
      var normalized = (0, _normalizr.normalize)(camelizedJson.items, (0, _normalizr.arrayOf)(_index2.article));
      return dispatch(receiveRelatedArticles(normalized, articleId, idsToFetch));
    }, function (error) {
      return dispatch(failToReceiveRelatedArticles(articleId, idsToFetch, error));
    });
  };
}

/* Fetch meta of articles according to one group uuid.
 * Group uuid could be Category, Tag or Topic uuid.
 * properties of meta: subtitle, name, heroImage, title, topics, publishedDate, slug, links, created and id
 * @param {string} uuid - Category, Tag or Topic uuid
 * @param {string} type - CATEGORY, TAG or TOPIC
 * @param {object} params - params for composing query param of api
 * @param {string} [params.sort=-publishedDate] -the way returned articles are sorted by
 * @param {object} params.where - where query param
 * @param {object} params.embedded - embedded query param
 * @param {boolean} isOnlyMeta - if true, only get metadata of articles. Otherwise, get full articles.
 */
function fetchArticlesByUuidIfNeeded() {
  var uuid = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];
  var type = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
  var params = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  var isOnlyMeta = arguments.length <= 3 || arguments[3] === undefined ? true : arguments[3];

  return function (dispatch, getState) {
    if (!uuid || _lodash2.default.get(getState(), ['articlesByUuids', uuid, 'hasMore']) === false) {
      return Promise.resolve();
    }

    switch (type) {
      case _index.SECTION:
        params = _setupWhereInParam('sections', [uuid], params);
        break;
      case _index.CATEGORY:
        params = _setupWhereInParam('categories', [uuid], params);
        break;
      case _index.TAG:
        params = _setupWhereInParam('tags', [uuid], params);
        break;
      case _index.TOPIC:
        params = _setupWhereInParam('topics', [uuid], params);
        break;
      default:
        return Promise.resolve();
    }

    if (!isOnlyMeta) {
      // add default embedded
      params.embedded = params.embedded ? params.embedded : (0, _index3.getArticleEmbeddedQuery)();
    }

    var url = _buildUrl(params, isOnlyMeta ? 'meta' : 'article');
    dispatch(requestArticlesByUuid(uuid, url));
    return _fetchArticles(url).then(function (response) {
      var camelizedJson = (0, _humps.camelizeKeys)(response);
      var normalized = (0, _normalizr.normalize)(camelizedJson.items, (0, _normalizr.arrayOf)(_index2.article));
      _lodash2.default.merge(normalized, { links: camelizedJson.links, meta: camelizedJson.meta });
      return dispatch(receiveArticlesByUuid(normalized, uuid));
    }, function (error) {
      return dispatch(failToReceiveArticlesByUuid(uuid, error));
    });
  };
}

/* Fetch meta of articles whose 'isFeature' field is true
 * properties of meta: subtitle, name, heroImage, title, topics, publishedDate, slug, links, created and id
 * @param {object} params - params for composing query param of api
 * @param {string} [params.sort=-publishedDate] -the way returned articles are sorted by
 * @param {object} params.where - where query param
 * @param {object} params.embedded - embedded query param
 * @param {boolean} isOnlyMeta - if true, only get metadata of articles. Otherwise, get full articles.
 */
function fetchFeatureArticles() {
  var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  var isOnlyMeta = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];

  var limit = 6;
  var page = 1;

  return function (dispatch) {
    params = params || {};
    params.where = _lodash2.default.merge({}, params.where, {
      isFeatured: true
    });
    params.max_results = params.max_results || limit;
    params.page = params.page || page;

    var url = _buildUrl(params, isOnlyMeta ? 'meta' : 'article');
    dispatch(requestFeatureArticles(url));
    return _fetchArticles(url).then(function (response) {
      var camelizedJson = (0, _humps.camelizeKeys)(response);
      var normalized = (0, _normalizr.normalize)(camelizedJson.items, (0, _normalizr.arrayOf)(_index2.article));
      return dispatch(receiveFeaturedArticles(normalized));
    }, function (error) {
      return dispatch(failToReceiveFeatureArticles(error));
    });
  };
}

// no need temporarily
/*
function _getListId(target = 'category') {
  if (__DEVELOPMENT__) { // eslint-disable-line
    return target === 'category' ? devCatListId : devTopicListId
  }
  return target === 'category' ? prodCatListId : prodTopicListId
}

export function fetchArticlesByTopicIdNameIfNeeded(topicName = '', params = {} , isOnlyMeta = true) {
  let listId = _getListId('topic')
  let topicId = listId[topicName]
  return fetchArticlesByTopicIdIfNeeded(topicId, params, isOnlyMeta)
}

function _fetchArticlesByListName(name = '', params = {}, isOnlyMeta = true, target) {
  let listId = _getListId(target)
  let id = listId[name]
  params = params || {}
  params.max_results = params.max_results || 10
  params.page = params.page || 1
  return target === 'category' ? fetchArticlesByCatIdIfNeeded(id, params, isOnlyMeta) : fetchArticlesByTagIdIfNeeded(id, params, isOnlyMeta)
}

export function fetchArticlesByCatNameIfNeeded(catName = '', params = {}, isOnlyMeta = true) {
  return _fetchArticlesByListName(catName, params, isOnlyMeta, 'category')
}

export function fetchArticlesByTagNameIfNeeded(tagName = '', params = {}, isOnlyMeta = true) {
  return _fetchArticlesByListName(tagName, params, isOnlyMeta, 'tag')
}

*/