'use strict';

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

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 _Leading = require('../components/Leading');

var _Leading2 = _interopRequireDefault(_Leading);

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


var MAXRESULT = 10;
var PAGE = 1;

if (process.env.BROWSER) {}

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

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

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

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

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

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

  _createClass(Topic, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var _props = this.props;
      var entities = _props.entities;
      var params = _props.params;

      var topicId = _lodash2.default.get(params, 'topicId');
      var topicName = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(entities, 'topics', {}), function (o) {
        return o.name == topicId || o.id == topicId;
      }), 'name');

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

      this.props.setPageType(_index.TOPIC);
      this.props.setPageTitle('', topicName ? topicName + _index.SITE_NAME.SEPARATOR + _index.SITE_NAME.FULL : _index.SITE_NAME.FULL);

      if (addthis) {
        addthis.addEventListener('addthis.menu.share', function () {
          _reactGa2.default.event({
            category: 'topic',
            action: 'click',
            label: 'social-share addthis'
          });
        });
      }
    }
  }, {
    key: 'componentWillMount',
    value: function componentWillMount() {
      var _props2 = this.props;
      var articlesByUuids = _props2.articlesByUuids;
      var fetchArticlesByUuidIfNeeded = _props2.fetchArticlesByUuidIfNeeded;
      var params = _props2.params;
      var fetchIndexArticles = _props2.fetchIndexArticles;
      var sectionList = _props2.sectionList;
      var topics = _props2.topics;

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

      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']);
      }

      this.props.fetchImages(_index.TOPIC, topicId, {
        max_results: 25
      });

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

      fetchArticlesByUuidIfNeeded(topicId, _index.TOPIC, {
        page: PAGE,
        max_results: MAXRESULT
      });
    }
  }, {
    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 topicId = _lodash2.default.get(params, 'topicId');

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

      fetchArticlesByUuidIfNeeded(topicId, _index.TOPIC, {
        page: PAGE,
        max_results: MAXRESULT
      });

      this.setState({
        topicId: nextProps.params.topicId
      });
    }
  }, {
    key: '_loadMore',
    value: function _loadMore() {
      var _props3 = this.props;
      var articlesByUuids = _props3.articlesByUuids;
      var fetchArticlesByUuidIfNeeded = _props3.fetchArticlesByUuidIfNeeded;
      var params = _props3.params;

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

      var articlesByCat = _lodash2.default.get(articlesByUuids, [topicId], {});
      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(topicId, _index.TOPIC, {
        page: page,
        max_results: MAXRESULT
      });

      _reactGa2.default.event({
        category: 'topic',
        action: 'click',
        label: 'loadMore'
      });
    }
  }, {
    key: '_renderAdSlot',
    value: function _renderAdSlot() {
      var _props4 = this.props;
      var topics = _props4.topics;
      var params = _props4.params;

      var topicId = _lodash2.default.get(params, 'topicId');
      var topicUUID = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(topics, 'items', {}), function (o) {
        return o.name == topicId || o.id == topicId;
      }), 'id');

      var dfpCode = _lodash2.default.get(topics, ['items', topicUUID, 'dfp'], '');
      var dfpMobileCode = _lodash2.default.get(topics, ['items', topicUUID, 'mobileDfp'], '');

      var desktopSize = [[970, 90], [970, 250], [300, 250]];
      var mobileSize = [[320, 100], [300, 250]];

      if (dfpCode == dfpMobileCode) {
        return dfpCode != '' ? _react2.default.createElement(
          'div',
          { style: { margin: '0 auto', 'marginBottom': '20px', 'maxWidth': '970px', textAlign: 'center' } },
          _react2.default.createElement(_reactDfp.AdSlot, { sizes: _lodash2.default.union(desktopSize, mobileSize),
            dfpNetworkId: _index.DFPID,
            slotId: 'topic_dfp',
            adUnit: dfpCode
          })
        ) : null;
      } else {
        return _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(
            'div',
            { style: { margin: '0 auto', 'marginBottom': '20px', 'maxWidth': '970px', textAlign: 'center' } },
            _react2.default.createElement(_reactDfp.AdSlot, { sizes: desktopSize,
              dfpNetworkId: _index.DFPID,
              slotId: 'topic_desktop_dfp',
              adUnit: _lodash2.default.get(topics, ['items', topicUUID, 'dfp'], ''),
              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: mobileSize,
              dfpNetworkId: _index.DFPID,
              slotId: 'topic_mobile_dfp',
              adUnit: _lodash2.default.get(topics, ['items', topicUUID, 'mobil_dfp'], ''),
              sizeMapping: [{ viewport: [1, 1], sizes: [[320, 100], [300, 250]] }, { viewport: [970, 200], sizes: [] }]
            })
          )
        );
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _props5 = this.props;
      var articlesByUuids = _props5.articlesByUuids;
      var entities = _props5.entities;
      var params = _props5.params;
      var sectionList = _props5.sectionList;
      var topics = _props5.topics;
      var location = _props5.location;

      var images = _lodash2.default.get(this.props.images, ['items', 'items']);

      var topicId = _lodash2.default.get(params, 'topicId');
      var topicUUID = _lodash2.default.get(_lodash2.default.find(_lodash2.default.get(topics, 'items', {}), function (o) {
        return o.name == topicId || o.id == topicId;
      }), 'id');

      var heroImage = _lodash2.default.get(topics, ['items', topicUUID, 'heroImage']);
      var heroVideo = _lodash2.default.get(topics, ['items', topicUUID, 'heroVideo']);
      var leading = _lodash2.default.get(topics, ['items', topicUUID, 'leading']);
      var ogDesc = _lodash2.default.get(topics, ['items', topicUUID, 'ogDescription']);
      var ogTitle = _lodash2.default.get(topics, ['items', topicUUID, 'ogTitle']);
      var topicName = _lodash2.default.get(topics, ['items', topicUUID, 'name']);

      var articles = (0, _index2.denormalizeArticles)(_lodash2.default.get(articlesByUuids, [topicId, 'items'], []), entities);
      var sectionListResponse = _lodash2.default.get(sectionList, 'response', {});

      var meta = {
        auto: { ograph: true },
        canonical: _index.SITE_META.URL + 'topic/' + topicId,
        description: ogDesc ? ogDesc : _index.SITE_META.DESC,
        meta: { property: {} },
        title: ogTitle ? ogTitle + _index.SITE_NAME.SEPARATOR + _index.SITE_NAME.FULL : topicName ? topicName + _index.SITE_NAME.SEPARATOR + _index.SITE_NAME.FULL : _index.SITE_NAME.FULL
      };

      return _react2.default.createElement(
        _reactDfp.DFPSlotsProvider,
        { dfpNetworkId: _index.DFPID },
        _react2.default.createElement(
          _reactDocumentMeta2.default,
          meta,
          _react2.default.createElement(_Sidebar2.default, { sectionList: sectionListResponse, topics: topics, pathName: location.pathname }),
          _react2.default.createElement(
            'div',
            { className: 'top' },
            _react2.default.createElement(_Header2.default, { sectionList: sectionListResponse, topics: topics, pathName: location.pathname }),
            _react2.default.createElement(
              'div',
              { className: 'topic-title' },
              _react2.default.createElement(
                'h2',
                null,
                'Title Here'
              )
            ),
            _react2.default.createElement(_Leading2.default, { leading: leading, mediaSource: { 'images': images, 'heroImage': heroImage, 'heroVideo': heroVideo, 'flag': 'topic' }, device: this.context.device })
          ),
          _react2.default.createElement(
            'div',
            { id: 'main', className: 'pusher middle' },
            _react2.default.createElement(_List2.default, {
              articles: articles,
              categories: entities.categories,
              title: topicName,
              hasMore: _lodash2.default.get(articlesByUuids, [topicId, 'hasMore']),
              loadMore: this.loadMore,
              pathName: this.props.location.pathname
            }),
            this.props.children,
            this.renderAdSlot(),
            _react2.default.createElement(_Footer2.default, { sectionList: sectionListResponse })
          ),
          _react2.default.createElement('style', { dangerouslySetInnerHTML: { __html: _lodash2.default.get(topics, ['items', topicUUID, 'style'], '') } }),
          _react2.default.createElement('script', { dangerouslySetInnerHTML: { __html: _lodash2.default.get(topics, ['items', topicUUID, 'javascript'], '') } }),
          _react2.default.createElement('script', { type: 'text/javascript', src: '//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-582e858f529d0edb' })
        )
      );
    }
  }]);

  return Topic;
}(_react.Component);

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

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

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