'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Tag = 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 _reactDocumentMeta = require('react-document-meta');

var _reactDocumentMeta2 = _interopRequireDefault(_reactDocumentMeta);

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

var _Footer2 = _interopRequireDefault(_Footer);

var _reactGa = require('react-ga');

var _reactGa2 = _interopRequireDefault(_reactGa);

var _Header = require('../components/Header');

var _Header2 = _interopRequireDefault(_Header);

var _List = require('../components/List');

var _List2 = _interopRequireDefault(_List);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _Sidebar = require('../components/Sidebar');

var _Sidebar2 = _interopRequireDefault(_Sidebar);

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; } /* global __DEVELOPMENT__ */


var MAXRESULT = 10;
var PAGE = 1;

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

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

      return store.dispatch((0, _articles.fetchArticlesByUuidIfNeeded)(params.tagId), _index.TAG, {
        page: PAGE,
        max_results: MAXRESULT
      }).then(function () {
        return store.dispatch((0, _articles.fetchIndexArticles)(['sections']));
      }).then(function () {
        return store.dispatch((0, _articles.fetchTopics)());
      });
    }
  }]);

  function Tag(props) {
    _classCallCheck(this, Tag);

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

    _this.loadMore = _this._loadMore.bind(_this);
    return _this;
  }

  _createClass(Tag, [{
    key: 'componentWillMount',
    value: function componentWillMount() {
      var _props = this.props;
      var articlesByUuids = _props.articlesByUuids;
      var fetchArticlesByUuidIfNeeded = _props.fetchArticlesByUuidIfNeeded;
      var params = _props.params;
      var fetchIndexArticles = _props.fetchIndexArticles;
      var topics = _props.topics;
      var sectionList = _props.sectionList;

      var tagId = _lodash2.default.get(params, 'tagId');

      if (!_lodash2.default.get(topics, 'fetched', undefined)) {
        this.props.fetchTopics();
      }

      // if fetched before, do nothing
      var checkSectionList = _lodash2.default.get(sectionList, 'fetched', undefined);
      if (!checkSectionList) {
        fetchIndexArticles(['sections']);
      }

      // if fetched before, do nothing
      if (_lodash2.default.get(articlesByUuids, [tagId, 'items', 'length'], 0) > 0) {
        return;
      }

      fetchArticlesByUuidIfNeeded(tagId, _index.TAG, {
        page: PAGE,
        max_results: MAXRESULT
      });
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      var _props2 = this.props;
      var entities = _props2.entities;
      var params = _props2.params;

      var tagId = _lodash2.default.get(params, 'tagId');
      var tagName = _lodash2.default.get(entities, ['tags', tagId, 'name'], '');

      _reactGa2.default.initialize(_index.GAID, { debug: __DEVELOPMENT__ });
      _reactGa2.default.pageview(this.props.location.pathname);

      this.props.setPageType(_index.TAG);
      this.props.setPageTitle('', tagName ? tagName + _index.SITE_NAME.SEPARATOR + _index.SITE_NAME.FULL : _index.SITE_NAME.FULL);
    }
  }, {
    key: 'componentWillUpdate',
    value: function componentWillUpdate(nextProps) {
      if (nextProps.location.pathname !== this.props.location.pathname) {
        _reactGa2.default.pageview(nextProps.location.pathname);
      }
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var articlesByUuids = nextProps.articlesByUuids;
      var fetchArticlesByUuidIfNeeded = nextProps.fetchArticlesByUuidIfNeeded;
      var params = nextProps.params;

      var tagId = _lodash2.default.get(params, 'tagId');

      // if fetched before, do nothing
      if (_lodash2.default.get(articlesByUuids, [tagId, 'items', 'length'], 0) > 0) {
        return;
      }

      fetchArticlesByUuidIfNeeded(tagId, _index.TAG, {
        page: PAGE,
        max_results: MAXRESULT
      });
    }
  }, {
    key: '_loadMore',
    value: function _loadMore() {
      var _props3 = this.props;
      var articlesByUuids = _props3.articlesByUuids;
      var fetchArticlesByUuidIfNeeded = _props3.fetchArticlesByUuidIfNeeded;
      var params = _props3.params;

      var tagId = _lodash2.default.get(params, 'tagId');
      var articlesByTag = _lodash2.default.get(articlesByUuids, [tagId], {});
      if (_lodash2.default.get(articlesByTag, 'hasMore') === false) {
        return;
      }

      var itemSize = _lodash2.default.get(articlesByTag, 'items.length', 0);
      var page = Math.floor(itemSize / MAXRESULT) + 1;

      _reactGa2.default.event({
        category: 'tag',
        action: 'click',
        label: 'loadMore'
      });

      fetchArticlesByUuidIfNeeded(tagId, _index.TAG, {
        page: page,
        max_results: MAXRESULT
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props4 = this.props;
      var articlesByUuids = _props4.articlesByUuids;
      var entities = _props4.entities;
      var params = _props4.params;
      var sectionList = _props4.sectionList;
      var topics = _props4.topics;
      var location = _props4.location;

      var tagId = _lodash2.default.get(params, 'tagId');
      var articles = (0, _index2.denormalizeArticles)(_lodash2.default.get(articlesByUuids, [tagId, 'items'], []), entities);
      var sectionListResponse = _lodash2.default.get(sectionList, 'response', {});
      var tagName = _lodash2.default.get(entities, ['tags', tagId, 'name'], '');
      var meta = {
        auto: { ograph: true },
        canonical: _index.SITE_META.URL + 'tag/' + tagId,
        description: _index.SITE_META.DESC,
        meta: { property: {} },
        title: tagName ? tagName + _index.SITE_NAME.SEPARATOR + _index.SITE_NAME.FULL : _index.SITE_NAME.FULL
      };

      return _react2.default.createElement(
        _reactDocumentMeta2.default,
        meta,
        _react2.default.createElement(_Sidebar2.default, { sectionList: sectionListResponse, topics: topics, pathName: location.pathname }),
        _react2.default.createElement(_Header2.default, { sectionList: sectionListResponse, topics: topics, pathName: location.pathname }),
        _react2.default.createElement(
          'div',
          { id: 'main', className: 'pusher' },
          _react2.default.createElement(_List2.default, {
            articles: articles,
            categories: entities.categories,
            hasMore: _lodash2.default.get(articlesByUuids, [tagId, 'hasMore']),
            loadMore: this.loadMore
          }),
          this.props.children,
          _react2.default.createElement(_Footer2.default, { sectionList: sectionListResponse })
        )
      );
    }
  }]);

  return Tag;
}(_react.Component);

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

Tag.contextTypes = {
  device: _react2.default.PropTypes.string
};

exports.Tag = Tag;
exports.default = (0, _reactRedux.connect)(mapStateToProps, { fetchArticlesByUuidIfNeeded: _articles.fetchArticlesByUuidIfNeeded, fetchIndexArticles: _articles.fetchIndexArticles, fetchTopics: _articles.fetchTopics, setPageType: _header.setPageType, setPageTitle: _header.setPageTitle })(Tag);