
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.fetchArticleIfNeeded = fetchArticleIfNeeded;

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

var _humps = require('humps');

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

var _normalizr = require('normalizr');

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

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);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

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

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 requestArticle(slug, url) {
  return {
    type: types.FETCH_ARTICLE_REQUEST,
    slug: slug,
    url: url
  };
}

function failToReceiveArticle(slug, error) {
  return {
    type: types.FETCH_ARTICLE_FAILURE,
    slug: slug,
    error: error,
    failedAt: Date.now()
  };
}

function receiveArticle(response, slug) {
  return {
    type: types.FETCH_ARTICLE_SUCCESS,
    slug: slug,
    response: response,
    receivedAt: Date.now()
  };
}

function fetchArticle(slug) {
  return function (dispatch) {
    var query = _qs2.default.stringify({ embedded: JSON.stringify((0, _index2.getArticleEmbeddedQuery)()) });
    var url = (0, _index2.formatUrl)('posts/' + slug + '?' + query);
    dispatch(requestArticle(slug, url));
    return (0, _isomorphicFetch2.default)(url).then(function (response) {
      var status = response.status;
      if (status === 404) {
        throw new _customError.NotFoundError('Article ' + slug + ' is not found');
      } else if (status >= 400) {
        throw new _customError.InternalServerError('Bad response from API, response: ' + JSON.stringify(response));
      }
      return response.json();
    }).then(function (response) {
      var camelizedJson = (0, _humps.camelizeKeys)(response);
      return dispatch(receiveArticle((0, _normalizr.normalize)(camelizedJson, _index.article), slug));
    }, function (error) {
      return dispatch(failToReceiveArticle(slug, error));
    });
  };
}

function shouldFetchArticle(state, slug) {
  var slugToId = _lodash2.default.get(state, 'slugToId', {});
  var articles = _lodash2.default.get(state, ['entities', 'articles'], {});
  if (_lodash2.default.get(articles, [slugToId[slug], 'content'])) {
    return false;
  }
  return true;
}

function fetchArticleIfNeeded(slug) {
  return function (dispatch, getState) {
    if (shouldFetchArticle(getState(), slug)) {
      return dispatch(fetchArticle(slug));
    }
    var state = getState();
    var response = {
      result: _lodash2.default.get(state, ['slugToId', slug])
    };
    return dispatch(receiveArticle(response, slug));
  };
}