/*eslint no-unused-vars:0, no-console:0 */
/* global __DEVELOPMENT__ */
'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

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

var _reactRedux = require('react-redux');

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

var _articles = require('../actions/articles');

var _header = require('../actions/header');

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _Daily = require('../components/Daily');

var _Daily2 = _interopRequireDefault(_Daily);

var _reactDocumentMeta = require('react-document-meta');

var _reactDocumentMeta2 = _interopRequireDefault(_reactDocumentMeta);

var _Features = require('../components/Features');

var _Features2 = _interopRequireDefault(_Features);

var _Footer = require('../components/Footer');

var _Footer2 = _interopRequireDefault(_Footer);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _SystemError = require('../components/SystemError');

var _SystemError2 = _interopRequireDefault(_SystemError);

var _TopNews = require('../components/TopNews');

var _TopNews2 = _interopRequireDefault(_TopNews);

var _async = require('async');

var _async2 = _interopRequireDefault(_async);

var _listId = require('../conf/list-id');

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var MAXRESULT = 10;
var PAGE = 1;

if (process.env.BROWSER) {}

var Home = function (_Component) {
  _inherits(Home, _Component);

  _createClass(Home, null, [{
    key: 'fetchData',
    value: function fetchData(_ref) {
      var store = _ref.store;

      var params = {
        page: PAGE,
        max_results: MAXRESULT
      };
      return new Promise(function (resolve, reject) {
        // load tagged articles in parallel
        _async2.default.parallel([function (callback) {
          store.dispatch((0, _articles.fetchFeatureArticles)()).then(function () {
            callback(null);
          });
        }, function (callback) {
          store.dispatch((0, _articles.fetchArticlesByUuidIfNeeded)((0, _index2.getCatId)(_index.REVIEW_CH_STR), _index.CATEGORY, params)).then(function () {
            callback(null);
          });
        }, function (callback) {
          store.dispatch((0, _articles.fetchArticlesByUuidIfNeeded)((0, _index2.getCatId)(_index.SPECIAL_TOPIC_CH_STR), _index.CATEGORY, params)).then(function () {
            callback(null);
          });
        }], function (err, results) {
          if (err) {
            console.warn('fetchData occurs error:', err);
          }
          resolve();
        });
      });
    }
  }]);

  function Home(props, context) {
    _classCallCheck(this, Home);

    var _this = _possibleConstructorReturn(this, (Home.__proto__ || Object.getPrototypeOf(Home)).call(this, props, context));

    _this.specialTopicListId = (0, _index2.getCatId)(_index.SPECIAL_TOPIC_CH_STR);
    _this.reviewListId = (0, _index2.getCatId)(_index.REVIEW_CH_STR);
    _this.loadMoreArticles = _this._loadMoreArticles.bind(_this, _this.specialTopicListId);
    return _this;
  }

  _createClass(Home, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.props.setPageType(_index.HOME);
    }
  }, {
    key: 'componentWillMount',
    value: function componentWillMount() {
      var _props = this.props;
      var fetchArticlesByUuidIfNeeded = _props.fetchArticlesByUuidIfNeeded;
      var fetchFeatureArticles = _props.fetchFeatureArticles;

      var params = {
        page: PAGE,
        max_results: MAXRESULT
      };
      fetchFeatureArticles();
      fetchArticlesByUuidIfNeeded(this.reviewListId, _index.CATEGORY, params);
      fetchArticlesByUuidIfNeeded(this.specialTopicListId, _index.CATEGORY, params);
    }
  }, {
    key: '_loadMoreArticles',
    value: function _loadMoreArticles(catId) {
      var _props2 = this.props;
      var articlesByUuids = _props2.articlesByUuids;
      var fetchArticlesByUuidIfNeeded = _props2.fetchArticlesByUuidIfNeeded;


      if (_lodash2.default.get(articlesByUuids, [catId, 'hasMore']) === false) {
        return;
      }

      var itemSize = _lodash2.default.get(articlesByUuids, [catId, 'items', 'length'], 0);
      var page = Math.floor(itemSize / MAXRESULT) + 1;
      fetchArticlesByUuidIfNeeded(catId, _index.CATEGORY, {
        page: page,
        max_results: MAXRESULT
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props3 = this.props;
      var articlesByUuids = _props3.articlesByUuids;
      var entities = _props3.entities;
      var featureArticles = _props3.featureArticles;

      var topnews_num = 5;
      var topnewsItems = (0, _index2.denormalizeArticles)(_lodash2.default.get(featureArticles, 'items', []), entities);
      var specialTopicItems = (0, _index2.denormalizeArticles)(_lodash2.default.get(articlesByUuids, [this.specialTopicListId, 'items'], []), entities);
      var reviewItems = (0, _index2.denormalizeArticles)(_lodash2.default.get(articlesByUuids, [this.reviewListId, 'items'], []), entities);
      var meta = {
        title: '報導者 The Reporter',
        description: '報導者致力於具有手作質感的深度報導，並勇於探索網路新工具與呈現方式，重視網路的公共性與開放性，結合各種進步價值與公民力量。',
        canonical: 'https://www.twreporter.org/',
        meta: { property: {} },
        auto: { ograph: true }
      };

      if (topnewsItems) {
        return _react2.default.createElement(
          _reactDocumentMeta2.default,
          meta,
          _react2.default.createElement(_TopNews2.default, { topnews: topnewsItems }),
          _react2.default.createElement(_Daily2.default, { daily: reviewItems
          }),
          _react2.default.createElement(_Features2.default, {
            features: specialTopicItems,
            hasMore: _lodash2.default.get(articlesByUuids, [this.specialTopicListId, 'hasMore']),
            loadMore: this.loadMoreArticles
          }),
          this.props.children,
          _react2.default.createElement(_Footer2.default, null)
        );
      } else {
        return _react2.default.createElement(_SystemError2.default, null);
      }
    }
  }]);

  return Home;
}(_react.Component);

function mapStateToProps(state) {
  return {
    articlesByUuids: state.articlesByUuids || {},
    entities: state.entities || {},
    featureArticles: state.featureArticles || {}
  };
}

exports.Home = Home;
exports.default = (0, _reactRedux.connect)(mapStateToProps, {
  fetchArticlesByUuidIfNeeded: _articles.fetchArticlesByUuidIfNeeded,
  fetchFeatureArticles: _articles.fetchFeatureArticles,
  setPageType: _header.setPageType
})(Home);