'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Category = 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 _AudioList = require('../components/AudioList');

var _AudioList2 = _interopRequireDefault(_AudioList);

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

var _reactDocumentMeta2 = _interopRequireDefault(_reactDocumentMeta);

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

var _Footer2 = _interopRequireDefault(_Footer);

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

var _VideoList = require('../components/VideoList');

var _VideoList2 = _interopRequireDefault(_VideoList);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

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 = 0;

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

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


      switch (params.category) {
        case 'videohub':
          return store.dispatch((0, _articles.fetchYoutubePlaylist)(MAXRESULT)).then(function () {
            return store.dispatch((0, _articles.fetchIndexArticles)(['sections'])).then(function () {
              return store.dispatch((0, _articles.fetchTopics)());
            });
          });
        case 'audio':
          return store.dispatch((0, _articles.fetchAudios)()).then(function () {
            return store.dispatch((0, _articles.fetchIndexArticles)(['sections'])).then(function () {
              return store.dispatch((0, _articles.fetchTopics)());
            });
          });
        default:
          return store.dispatch((0, _articles.fetchArticlesByUuidIfNeeded)(params.category, _index.CATEGORY), {
            page: PAGE,
            max_results: MAXRESULT
          }).then(function () {
            return store.dispatch((0, _articles.fetchIndexArticles)(['sections']));
          }).then(function () {
            return store.dispatch((0, _articles.fetchTopics)());
          });
      }
    }
  }]);

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

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

    var category = _this.props.params.category;
    _this.state = {
      catId: category
    };
    _this.loadMore = _this._loadMore.bind(_this);
    _this.loadMoreVideo = _this._loadMoreVideo.bind(_this);
    _this.loadMoreAudio = _this._loadMoreAudio.bind(_this);
    _this.renderList = _this._renderList.bind(_this);
    return _this;
  }

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

      var catId = this.state.catId;

      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
      var checkYoutubePlaylist = _lodash2.default.get(youtubePlaylist, 'fetched', undefined);
      if (!checkYoutubePlaylist) {
        fetchYoutubePlaylist(MAXRESULT);
      }

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

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

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

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

      if (nextProps.location.pathname !== this.props.location.pathname) {
        if (section != null) _reactGa2.default.set({ 'contentGroup1': sectionName });
        _reactGa2.default.pageview(nextProps.location.pathname);
      }
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      _reactDfp.DFPManager.load();
      _reactDfp.DFPManager.refresh();
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var articlesByUuids = nextProps.articlesByUuids;
      var fetchArticlesByUuidIfNeeded = nextProps.fetchArticlesByUuidIfNeeded;
      var params = nextProps.params;

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

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

      fetchArticlesByUuidIfNeeded(catId, _index.CATEGORY, {
        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, 'category');

      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.CATEGORY, {
        page: page,
        max_results: MAXRESULT
      });

      _reactGa2.default.event({
        category: 'category',
        action: 'click',
        label: 'loadMore'
      });
    }
  }, {
    key: '_loadMoreVideo',
    value: function _loadMoreVideo() {
      this.props.fetchYoutubePlaylist(MAXRESULT, this.props.youtubePlaylist.nextPageToken);
      _reactGa2.default.event({
        category: 'category',
        action: 'click',
        label: 'loadMore'
      });
    }
  }, {
    key: '_loadMoreAudio',
    value: function _loadMoreAudio() {
      var audios = this.props.audios;

      this.props.fetchAudios({
        page: Math.floor(_lodash2.default.get(audios, ['items', 'length'], 0) / MAXRESULT) + 1,
        max_results: MAXRESULT
      });
      _reactGa2.default.event({
        category: 'category',
        action: 'click',
        label: 'loadMore'
      });
    }
  }, {
    key: '_renderList',
    value: function _renderList() {
      var _props3 = this.props;
      var articlesByUuids = _props3.articlesByUuids;
      var entities = _props3.entities;
      var params = _props3.params;
      var sectionList = _props3.sectionList;
      var youtubePlaylist = _props3.youtubePlaylist;
      var audios = _props3.audios;

      var catId = _lodash2.default.get(params, 'category');
      var section = _lodash2.default.find(_lodash2.default.get(sectionList, ['response', 'sections']), function (o) {
        return _lodash2.default.find(o.categories, { 'name': catId });
      });
      var sectionName = _lodash2.default.get(section, 'name', '');
      var articles = (0, _index2.denormalizeArticles)(_lodash2.default.get(articlesByUuids, [catId, 'items'], []), entities);
      var category = _lodash2.default.get(params, 'category', null);
      var catName = _lodash2.default.get(sectionList.response, ['categories', category, 'title'], null);

      switch (catId) {
        case 'videohub':
          return _react2.default.createElement(_VideoList2.default, {
            playlist: youtubePlaylist.items,
            title: 'VideoHub',
            hasMore: _lodash2.default.get(youtubePlaylist, ['nextPageToken']),
            loadMore: this.loadMoreVideo
          });
        case 'audio':
          return _react2.default.createElement(_AudioList2.default, {
            audios: audios.items,
            title: 'Audio',
            hasMore: _lodash2.default.get(audios, ['meta', 'total']) > _lodash2.default.get(audios, ['items', 'length']),
            loadMore: this.loadMoreAudio
          });
        default:
          return _react2.default.createElement(_List2.default, {
            articles: articles,
            categories: entities.categories,
            section: sectionName,
            title: catName,
            hasMore: _lodash2.default.get(articlesByUuids, [catId, 'hasMore']),
            loadMore: this.loadMore
          });
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _props4 = this.props;
      var params = _props4.params;
      var sectionList = _props4.sectionList;
      var topics = _props4.topics;
      var location = _props4.location;


      var category = _lodash2.default.get(params, 'category', null);
      var catId = _lodash2.default.get(sectionList.response, ['categories', category, 'id'], null);
      var section = _lodash2.default.find(_lodash2.default.get(sectionList, ['response', 'sections']), function (o) {
        return _lodash2.default.find(o.categories, { 'id': catId });
      });
      var sectionName = _lodash2.default.get(section, 'name', '');

      var catName = _lodash2.default.get(sectionList.response, ['categories', category, 'title'], null);
      var meta = {
        title: catName ? catName + _index.SITE_NAME.SEPARATOR + _index.SITE_NAME.FULL : _index.SITE_NAME.FULL,
        description: _index.SITE_META.DESC,
        canonical: _index.SITE_META.URL + 'category/' + category,
        meta: { property: {} },
        auto: { ograph: true }
      };

      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[sectionName] + '_970x250_HD',
                adUnit: 'mm_pc_' + _index.AD_UNIT_PREFIX[sectionName] + '_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: [[320, 100], [300, 250]],
                dfpNetworkId: _index.DFPID,
                slotId: 'mm_mobile_' + _index.AD_UNIT_PREFIX[sectionName] + '_300x250_HD',
                adUnit: 'mm_mobile_' + _index.AD_UNIT_PREFIX[sectionName] + '_300x250_HD',
                sizeMapping: [{ viewport: [1, 1], sizes: [[320, 100], [300, 250]] }, { viewport: [970, 200], sizes: [] }]
              })
            ),
            this.renderList(),
            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[sectionName] + '_970x90_FT',
                adUnit: 'mm_pc_' + _index.AD_UNIT_PREFIX[sectionName] + '_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[sectionName] + '_320x100_FT',
                adUnit: 'mm_mobile_' + _index.AD_UNIT_PREFIX[sectionName] + '_320x100_FT',
                sizeMapping: [{ viewport: [1, 1], sizes: [[320, 100], [300, 250]] }, { viewport: [970, 200], sizes: [] }]
              })
            ),
            _react2.default.createElement(_Footer2.default, { sectionList: sectionList.response })
          )
        )
      );
    }
  }]);

  return Category;
}(_react.Component);

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

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

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