'use strict';

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

var _Header2 = _interopRequireDefault(_Header);

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

var _Sidebar2 = _interopRequireDefault(_Sidebar);

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

var _Footer2 = _interopRequireDefault(_Footer);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _List2 = _interopRequireDefault(_List);

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;

// english to chinese of category

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

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

      var keyword = params.keyword;
      return store.dispatch((0, _articles.makeSearchQuery)(encodeURIComponent(keyword) + '&offset=' + PAGE + '&length=' + MAXRESULT)).then(function () {
        return store.dispatch((0, _articles.fetchIndexArticles)(['sections']));
      }).then(function () {
        return store.dispatch((0, _articles.fetchTopics)());
      });
    }
  }]);

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

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

    var keyword = _this.props.params.keyword;
    _this.state = {
      keyword: keyword,
      nlength: MAXRESULT
    };
    _this.loadMore = _this._loadMore.bind(_this);
    return _this;
  }

  _createClass(Search, [{
    key: 'componentWillMount',
    value: function componentWillMount() {
      // const { articlesByUuids, fetchArticlesByUuidIfNeeded, fetchIndexArticles, searchResult, makeSearchQuery, sectionList } = this.props
      var _props = this.props;
      var fetchIndexArticles = _props.fetchIndexArticles;
      var makeSearchQuery = _props.makeSearchQuery;
      var sectionList = _props.sectionList;
      var topics = _props.topics;
      var searchResult = _props.searchResult;

      var keyword = this.state.keyword;

      var checkSearchResult = _lodash2.default.get(searchResult, 'response', undefined);
      if (!checkSearchResult) {
        makeSearchQuery(encodeURIComponent(keyword) + '&offset=' + PAGE + '&length=' + MAXRESULT).then(function () {
          // console.log( searchResult )
          return;
        });
      }

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

      // if fetched before, do nothing
      if (_lodash2.default.get(sectionList, ['response', 'length'], 0) == 0) {
        fetchIndexArticles(['sections']);
      }
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      var params = this.props.params;

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

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

      this.props.setPageType(_index.SEARCH);
      this.props.setPageTitle('', keyword ? '「' + keyword + '」' + +_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: '_loadMore',
    value: function _loadMore() {
      var _props2 = this.props;
      var searchResult = _props2.searchResult;
      var makeSearchQuery = _props2.makeSearchQuery;
      var params = _props2.params;

      var keyword = _lodash2.default.get(params, 'keyword', null);
      var nlength = this.state.nlength;

      if (_lodash2.default.get(searchResult, ['response', 'nbHits'], 0) <= _lodash2.default.get(searchResult, ['response', 'length'], 0)) {
        return;
      }

      var length = nlength + MAXRESULT;

      makeSearchQuery(encodeURIComponent(keyword) + '&offset=' + 0 + '&length=' + length).then(function () {
        // console.log( searchResult )
        return;
      });

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

      this.setState({
        nlength: length
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props3 = this.props;
      var entities = _props3.entities;
      var params = _props3.params;
      var sectionList = _props3.sectionList;
      var searchResult = _props3.searchResult;
      var topics = _props3.topics;
      var location = _props3.location;

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

      var meta = {
        title: keyword ? '「' + keyword + '」' + _index.SITE_NAME.SEPARATOR + _index.SITE_NAME.FULL : _index.SITE_NAME.FULL,
        description: _index.SITE_META.DESC,
        canonical: _index.SITE_META.URL + 'search/' + keyword,
        meta: { property: {} },
        auto: { ograph: true }
      };

      return _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(_List2.default, {
            articles: _lodash2.default.get(searchResult, ['response', 'hits'], []),
            categories: entities.categories,
            title: params.keyword,
            hasMore: _lodash2.default.get(searchResult, ['response', 'nbHits'], 0) > _lodash2.default.get(searchResult, ['response', 'length'], 0),
            loadMore: this.loadMore
          }),
          this.props.children,
          _react2.default.createElement(_Footer2.default, { sectionList: sectionList.response })
        )
      );
    }
  }]);

  return Search;
}(_react.Component);

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

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

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