'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Section = 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 _reactDfp = require('react-dfp');

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

var _humps = require('humps');

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

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

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

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _ChoicesFull = require('../components/ChoicesFull');

var _ChoicesFull2 = _interopRequireDefault(_ChoicesFull);

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

var _reactDocumentMeta2 = _interopRequireDefault(_reactDocumentMeta);

var _Featured = require('../components/Featured');

var _Featured2 = _interopRequireDefault(_Featured);

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

var _Footer2 = _interopRequireDefault(_Footer);

var _FooterFull = require('../components/FooterFull');

var _FooterFull2 = _interopRequireDefault(_FooterFull);

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

var _Header2 = _interopRequireDefault(_Header);

var _HeaderFull = require('../components/HeaderFull');

var _HeaderFull2 = _interopRequireDefault(_HeaderFull);

var _LatestStories = require('../components/LatestStories');

var _LatestStories2 = _interopRequireDefault(_LatestStories);

var _Leading = require('../components/Leading');

var _Leading2 = _interopRequireDefault(_Leading);

var _LeadingFull = require('../components/LeadingFull');

var _LeadingFull2 = _interopRequireDefault(_LeadingFull);

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

var _SidebarFull = require('../components/SidebarFull');

var _SidebarFull2 = _interopRequireDefault(_SidebarFull);

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

var _reactGa2 = _interopRequireDefault(_reactGa);

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__ */


if (process.env.BROWSER) {}

var MAXRESULT = 10;
var PAGE = 1;

// english to chinese of category

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

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

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

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

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

    var section = _this.props.params.section;
    _this.state = {
      catId: section
    };
    _this.loadMore = _this._loadMore.bind(_this);
    return _this;
  }

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

      var catId = this.state.catId;

      //TODO: We should not get all the keys
      var checkSectionList = _lodash2.default.get(sectionList, 'fetched', undefined);
      var checkSectionFeatured = _lodash2.default.get(sectionFeatured, 'fetched', undefined);
      if (!checkSectionList || !checkSectionFeatured) {
        fetchIndexArticles(['sections', 'sectionfeatured']);
      }

      var section = _lodash2.default.get(this.props.params, 'section', null);
      var sectionID = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(sectionList, ['response', 'sections']), { name: section }), ['id'], null);

      this.props.fetchEvent({
        max_results: 1,
        where: {
          sections: sectionID
        }
      });

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

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

      fetchArticlesByUuidIfNeeded(catId, _index.SECTION, {
        page: PAGE,
        max_results: MAXRESULT
      });
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      var section = _lodash2.default.get(this.props.params, 'section', null);
      var catName = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(this.props.sectionList, ['response', 'sections']), { name: section }), ['title'], null);

      _reactGa2.default.initialize(_index.GAID, { debug: __DEVELOPMENT__ });
      if (section != null) _reactGa2.default.set({ 'contentGroup1': catName });
      _reactGa2.default.pageview(this.props.location.pathname);

      this.props.setPageType(_index.SECTION);
      this.props.setPageTitle('', catName ? catName + _index.SITE_NAME.SEPARATOR + _index.SITE_NAME.FULL : _index.SITE_NAME.FULL);
    }
  }, {
    key: 'componentWillUpdate',
    value: function componentWillUpdate(nextProps) {
      var section = _lodash2.default.get(nextProps.params, 'section', null);
      var catName = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(nextProps.sectionList, ['response', 'sections']), { name: section }), ['title'], null);
      var sectionID = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(nextProps.sectionList, ['response', 'sections']), { name: section }), ['id'], null);

      if (nextProps.location.pathname !== this.props.location.pathname) {
        if (section != null) _reactGa2.default.set({ 'contentGroup1': catName });
        _reactGa2.default.pageview(nextProps.location.pathname);

        this.props.fetchEvent({
          max_results: 1,
          where: {
            sections: sectionID
          }
        });
      }
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var articlesByUuids = nextProps.articlesByUuids;
      var fetchArticlesByUuidIfNeeded = nextProps.fetchArticlesByUuidIfNeeded;
      var params = nextProps.params;

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

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

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

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

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

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

      fetchArticlesByUuidIfNeeded(catId, _index.SECTION, {
        page: page,
        max_results: MAXRESULT
      });

      _reactGa2.default.event({
        category: 'section',
        action: 'click',
        label: 'loadMore'
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props3 = this.props;
      var articlesByUuids = _props3.articlesByUuids;
      var entities = _props3.entities;
      var location = _props3.location;
      var params = _props3.params;
      var sectionFeatured = _props3.sectionFeatured;
      var sectionList = _props3.sectionList;
      var topics = _props3.topics;

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

      var articles = (0, _index2.denormalizeArticles)(_lodash2.default.get(articlesByUuids, [catId, 'items'], []), entities);
      var featured = _lodash2.default.filter(entities.articles, function (v, k) {
        return _lodash2.default.indexOf(_lodash2.default.get(sectionFeatured, ['items', (0, _humps.camelize)(catId)], []), k) > -1;
      });

      var section = _lodash2.default.get(params, 'section', null);
      var sectionLogo = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(sectionList, ['response', 'sections']), { name: section }), ['logo'], null);
      var sectionStyle = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(sectionList, ['response', 'sections']), { name: section }), ['style'], null);
      var catName = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(sectionList, ['response', 'sections']), { name: section }), ['title'], null);
      var catDesc = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(sectionList, ['response', 'sections']), { name: section }), ['description'], null);
      var customCSS = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(sectionList, ['response', 'sections']), { name: section }), ['css'], null);
      var customJS = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(sectionList, ['response', 'sections']), { name: section }), ['javascript'], null);
      var meta = {
        title: catName ? catName + _index.SITE_NAME.SEPARATOR + _index.SITE_NAME.FULL : _index.SITE_NAME.FULL,
        description: catDesc,
        canonical: _index.SITE_META.URL + 'section/' + section,
        meta: { property: {} },
        auto: { ograph: true }
      };

      var event = _lodash2.default.get(this.props.event, ['items', 0]);
      var embed = _lodash2.default.get(event, ['embed']);
      var eventType = _lodash2.default.get(event, ['eventType']);
      var eventPeriod = [_lodash2.default.get(event, ['startDate']), _lodash2.default.get(event, ['endDate'])];
      var image = _lodash2.default.get(event, ['image']);
      // const isFeatured = _.get(event, [ 'isFeatured' ])
      var video = _lodash2.default.get(event, ['video']);

      if (sectionStyle == 'feature') {
        return _react2.default.createElement(
          _reactDfp.DFPSlotsProvider,
          { dfpNetworkId: _index.DFPID },
          _react2.default.createElement(
            _reactDocumentMeta2.default,
            meta,
            _react2.default.createElement(_Sidebar2.default, { sectionList: sectionList.response, topics: topics, pathName: location.pathname }),
            _react2.default.createElement(_Header2.default, { sectionList: sectionList.response, topics: topics, pathName: location.pathname }),
            _react2.default.createElement(
              'div',
              { id: 'main', className: 'pusher' },
              _react2.default.createElement(
                'div',
                { style: { margin: '0 auto', 'marginBottom': '20px', 'maxWidth': '970px', textAlign: 'center' } },
                _react2.default.createElement(_reactDfp.AdSlot, { sizes: [[970, 90], [970, 250]],
                  dfpNetworkId: _index.DFPID,
                  slotId: 'mm_pc_' + _index.AD_UNIT_PREFIX[section] + '_970x250_HD',
                  adUnit: 'mm_pc_' + _index.AD_UNIT_PREFIX[section] + '_970x250_HD',
                  sizeMapping: [{ viewport: [0, 0], sizes: [] }, { viewport: [970, 200], sizes: [[970, 90], [970, 250]] }]
                })
              ),
              _react2.default.createElement(
                'div',
                { style: { margin: '0 auto', 'marginBottom': '20px', 'maxWidth': '320px', textAlign: 'center' } },
                _react2.default.createElement(_reactDfp.AdSlot, { sizes: [[300, 250], [320, 100]],
                  dfpNetworkId: _index.DFPID,
                  slotId: 'mm_mobile_' + _index.AD_UNIT_PREFIX[section] + '_300x250_HD',
                  adUnit: 'mm_mobile_' + _index.AD_UNIT_PREFIX[section] + '_300x250_HD',
                  sizeMapping: [{ viewport: [1, 1], sizes: [[300, 250], [320, 100]] }, { viewport: [970, 200], sizes: [] }]
                })
              ),
              _react2.default.createElement(_Leading2.default, { leading: eventType, mediaSource: { 'heroImage': image, 'heroVideo': video, 'embed': embed, 'eventPeriod': eventPeriod, 'flag': 'event', 'isFeatured': true }, device: this.context.device, pathName: location.pathname }),
              _react2.default.createElement(_Featured2.default, { articles: featured, categories: entities.categories }),
              _react2.default.createElement(_List2.default, {
                articles: articles,
                categories: entities.categories,
                section: section,
                title: catName,
                hasMore: _lodash2.default.get(articlesByUuids, [catId, 'hasMore']),
                loadMore: this.loadMore,
                pathName: this.props.location.pathname
              }),
              this.props.children,
              _react2.default.createElement(
                'div',
                { style: { margin: '0 auto', 'marginBottom': '20px', 'maxWidth': '970px', textAlign: 'center' } },
                _react2.default.createElement(_reactDfp.AdSlot, { sizes: [[970, 90]],
                  dfpNetworkId: _index.DFPID,
                  slotId: 'mm_pc_' + _index.AD_UNIT_PREFIX[section] + '_970x90_FT',
                  adUnit: 'mm_pc_' + _index.AD_UNIT_PREFIX[section] + '_970x90_FT',
                  sizeMapping: [{ viewport: [0, 0], sizes: [] }, { viewport: [970, 200], sizes: [[970, 90], [970, 250], [300, 250]] }]
                })
              ),
              _react2.default.createElement(
                'div',
                { style: { margin: '0 auto', 'marginBottom': '20px', 'maxWidth': '320px', textAlign: 'center' } },
                _react2.default.createElement(_reactDfp.AdSlot, { sizes: [[320, 100]],
                  dfpNetworkId: _index.DFPID,
                  slotId: 'mm_mobile_' + _index.AD_UNIT_PREFIX[section] + '_320x100_FT',
                  adUnit: 'mm_mobile_' + _index.AD_UNIT_PREFIX[section] + '_320x100_FT',
                  sizeMapping: [{ viewport: [1, 1], sizes: [[320, 100], [300, 250]] }, { viewport: [970, 200], sizes: [] }]
                })
              ),
              _react2.default.createElement(_Footer2.default, { sectionList: sectionList.response })
            ),
            _react2.default.createElement('style', { dangerouslySetInnerHTML: { __html: customCSS } }),
            _react2.default.createElement('script', { dangerouslySetInnerHTML: { __html: customJS } })
          )
        );
      } else {
        return _react2.default.createElement(
          _reactDfp.DFPSlotsProvider,
          { dfpNetworkId: _index.DFPID },
          _react2.default.createElement(
            _reactDocumentMeta2.default,
            meta,
            _react2.default.createElement(_SidebarFull2.default, { pathName: location.pathname, sectionList: sectionList.response }),
            _react2.default.createElement(_HeaderFull2.default, { pathName: location.pathname, sectionLogo: sectionLogo }),
            _react2.default.createElement(_LeadingFull2.default, {
              articles: articles,
              pathName: location.pathname,
              section: section,
              title: catName }),
            _react2.default.createElement(_ChoicesFull2.default, {
              articles: featured,
              authors: entities.authors,
              categories: entities.categories,
              pathName: location.pathname }),
            _react2.default.createElement(_LatestStories2.default, {
              articles: articles,
              hasMore: _lodash2.default.get(articlesByUuids, [catId, 'hasMore']),
              loadMore: this.loadMore,
              pathName: location.pathname }),
            _react2.default.createElement(_FooterFull2.default, { pathName: location.pathname, sectionList: sectionList.response, sectionLogo: sectionLogo }),
            _react2.default.createElement('style', { dangerouslySetInnerHTML: { __html: customCSS } }),
            _react2.default.createElement('script', { dangerouslySetInnerHTML: { __html: customJS } })
          )
        );
      }
    }
  }]);

  return Section;
}(_react.Component);

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

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

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