'use strict';

var toConsumableArray = require('./toConsumableArray-d7797c2b.js');
var _extends = require('./extends-be0d85bc.js');
var inherits = require('./inherits-e47b5342.js');
var React = require('react');
var index = require('./index-7435b964.js');
var Container = require('react-bootstrap/Container');
var Row = require('react-bootstrap/Row');
var Col = require('react-bootstrap/Col');
var Card = require('react-bootstrap/Card');
var visibilitySensor = require('./visibility-sensor-56020df6.js');
var moment = require('./moment-f730814d.js');
var Router = require('next/router');
var index$1 = require('./index-65621b6c.js');
var get = require('./get-5839e5b5.js');
var debounce = require('./debounce-d4a2369b.js');
var index_es = require('./index.es-1ab8dda7.js');
var urlFor = require('./urlFor.js');
var main = require('./main-812888f1.js');
var entities = require('./entities-df1aed86.js');
require('./_commonjsHelpers-06173234.js');
require('./core.get-iterator-method-5643aa10.js');
require('./_iter-detect-b1df62f0.js');
require('./_object-sap-d1978572.js');
require('./define-property-e8404b64.js');
require('./typeof-220bbf73.js');
require('./web.dom.iterable-d98303e0.js');
require('./_is-array-54228b29.js');
require('./_library-dd23b178.js');
require('prop-types');
require('react-dom');
require('./isSymbol-03abbdf0.js');
require('./eq-5fc26c07.js');
require('./toNumber-5e1fac58.js');
require('./slicedToArray-067dd3bc.js');
require('./index-d48b231c.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var Container__default = /*#__PURE__*/_interopDefaultLegacy(Container);
var Row__default = /*#__PURE__*/_interopDefaultLegacy(Row);
var Col__default = /*#__PURE__*/_interopDefaultLegacy(Col);
var Card__default = /*#__PURE__*/_interopDefaultLegacy(Card);

var DeckQueue = function (_React$Component) {
  inherits._inherits(DeckQueue, _React$Component);

  function DeckQueue() {
    var _ref;

    var _temp, _this, _ret;

    inherits._classCallCheck(this, DeckQueue);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = inherits._possibleConstructorReturn(this, (_ref = DeckQueue.__proto__ || inherits._Object$getPrototypeOf(DeckQueue)).call.apply(_ref, [this].concat(args))), _this), _this.page = _this.props.page, _this.data = _this.props.dataRecord, _this.query = _this.props.query, _this.params = _this.props.params, _this.client = _this.props.client, _this.pointer = _this.props.pointer ? _this.props.pointer : false, _this.pointerArray = _this.props.pointerArray ? _this.props.pointerArray : false, _this.defaultImage = _this.props.defaultImage ? _this.props.defaultImage : '/placeholder.jpg', _this.imageHeight = _this.props.imageHeight ? _this.props.imageHeight : 270, _this.state = {
      data: _this.data,
      per: _this.params ? _this.params.itemsPerPage : 10,
      page: _this.props.currentPage || 1,
      from: _this.params ? _this.params.from : 0,
      to: _this.params ? _this.params.to : 10,
      total_pages: null,
      scrolling: true,
      query: _this.query,
      currentPage: _this.props.currentPage || 1,
      lastDataSize: _this.data ? _this.data.length : 0
    }, _this.loadMore = debounce.debounce_1(function () {
      _this.setState(function (state) {
        var page = state.page,
            from = state.from,
            per = state.per,
            to = state.to;

        return {
          page: page + 1,
          from: from + per,
          to: to + per
        };
      }, _this.loadData);
    }, 0), _this.loadData = function () {
      var _this$state = _this.state,
          from = _this$state.from,
          to = _this$state.to,
          data = _this$state.data,
          query = _this$state.query,
          page = _this$state.page;


      var params = _extends._extends({}, _this.params, { from: from, to: to
        // const queryUpdated = query.replace('$from', params.from).replace('$to', params.to)
      });_this.client.fetch(query, params).then(function (dataArr) {
        if (_this.pointer && _this.pointerArray) {
          var pointer = _this.pointer;
          dataArr = dataArr[_this.pointerArray][pointer];
        }
        dataArr = dataArr.map(function (item) {
          return _extends._extends({}, item, {
            pageNumber: page
          });
        });

        _this.setState(function () {
          if (dataArr.length > 0) {
            return {
              data: [].concat(toConsumableArray._toConsumableArray(data), toConsumableArray._toConsumableArray(dataArr)),
              lastDataSize: dataArr.length,
              scrolling: true
            };
          } else {
            return {
              scrolling: false,
              lastDataSize: 0
            };
          }
        });
      });
    }, _this.renderCardImage = function (row) {
      if (row.thumbnail && row.thumbnail.asset) {
        var url = urlFor({
          client: _this.client,
          source: row.thumbnail,
          imageHeight: _this.imageHeight || null,
          imageWidth: _this.props.imageWidth || null,
          imageFit: _this.props.imageFit || null
        });
        return url;
      } else {
        return _this.defaultImage;
      }
    }, _this.changePageNumber = function (pageNumber) {
      var _this$props = _this.props,
          seoPaginate = _this$props.seoPaginate,
          pageview = _this$props.pageview,
          router = _this$props.router;
      var currentPage = _this.state.currentPage;

      if (seoPaginate) {
        var path = router.asPath;
        var qrIndex = path.indexOf('?');
        var pathname = router.pathname;
        var queryString = '';

        if (qrIndex > 0) {
          path = path.substring(1, qrIndex);

          var partialQS = router.asPath.substring(qrIndex + 1);
          var partialQSArr = partialQS.split('&');

          // exclude page=xxx from query string
          partialQSArr.map(function (item) {
            var itemArr = item.split('=');
            var key = itemArr[0];
            var val = itemArr[1];

            if (key !== 'page') {
              queryString += (queryString.length === 0 ? '' : '&') + key + '=' + val;
            }
          });
        }

        if (queryString.length > 0) {
          path += '?' + queryString;
        }

        pageNumber = parseInt(pageNumber);

        if (currentPage !== pageNumber) {
          index.lib_3.refresh();

          _this.setState({
            currentPage: pageNumber
          }, function () {
            if (path[0] !== '/') {
              path = '/' + path;
            }

            var newPath = pageNumber === 1 ? '' + path : path + '?page=' + pageNumber;

            if (pageview) {
              pageview(newPath);
            }

            router.push(pathname, newPath, {
              shallow: true
            });
          });
        }
      }
    }, _this.renderMobileAd = function (index, numberOfItemsBeforeAd) {
      var rightItems = _this.props.rightItems;

      var i = ((index + 1) / numberOfItemsBeforeAd - 1) % rightItems.length;
      return React__default["default"].createElement(
        'div',
        { style: { display: 'flex', flex: '1 0 auto' } },
        rightItems[i].component
      );
    }, _this.renderManualPagination = function (_ref2) {
      var nextPagePostsCount = _ref2.nextPagePostsCount;
      var _this$state2 = _this.state,
          currentPage = _this$state2.currentPage,
          per = _this$state2.per,
          lastDataSize = _this$state2.lastDataSize;

      return React__default["default"].createElement(
        'div',
        { className: 'd-flex justify-content-between' },
        currentPage && currentPage > 1 && React__default["default"].createElement(
          'a',
          { href: '?page=' + (currentPage - 1) },
          '<< Previous'
        ),
        !(lastDataSize < per) && nextPagePostsCount > 0 && React__default["default"].createElement(
          'a',
          { href: '?page=' + (currentPage + 1) },
          'Next >>'
        )
      );
    }, _temp), inherits._possibleConstructorReturn(_this, _ret);
  }

  inherits._createClass(DeckQueue, [{
    key: 'cardLoader',
    value: function cardLoader(page, columns, variant) {
      var _this2 = this;

      var mode = variant && variant === 'right' ? 'row-reverse' : 'row';
      var lgVar = Math.floor(12 / columns);
      var numberOfItemsBeforeAd = 6;

      return React__default["default"].createElement(
        Row__default["default"],
        null,
        this.state.data && this.state.data.map(function (row, index) {
          var pageNumber = row.pageNumber || _this2.state.page;
          // const thumbnailURL = get(row, 'thumbnail.asset.url', this.props.defaultImage)

          return React__default["default"].createElement(
            React__default["default"].Fragment,
            { key: index },
            React__default["default"].createElement(
              visibilitySensor.VisibilitySensor,
              {
                onChange: function onChange(isVisible) {
                  isVisible && _this2.changePageNumber(pageNumber);
                } },
              React__default["default"].createElement(
                Col__default["default"],
                { md: 12, lg: lgVar, style: { display: 'flex', flex: '1 0 auto' } },
                React__default["default"].createElement(
                  Card__default["default"],
                  { className: 'queue-card', style: { borderTop: '1px solid #EEE' } },
                  React__default["default"].createElement(
                    Row__default["default"],
                    { style: { flexDirection: mode } },
                    (row.thumbnail && row.thumbnail.asset || _this2.props.defaultImage) && React__default["default"].createElement(
                      Col__default["default"],
                      { md: 12, lg: 4 },
                      React__default["default"].createElement(
                        'a',
                        { href: _this2.page + '/' + get.get_1(row, 'url.current') },
                        React__default["default"].createElement(
                          index$1.LazyLoad,
                          { height: _this2.props.imageHeight },
                          React__default["default"].createElement(Card__default["default"].Img, { variant: 'top', src: _this2.renderCardImage(row), alt: row.thumbnail && row.thumbnail.asset ? row.thumbnail.asset.originalFilename : '' })
                        )
                      )
                    ),
                    React__default["default"].createElement(
                      Col__default["default"],
                      null,
                      React__default["default"].createElement(
                        Card__default["default"].Body,
                        { style: { padding: '20px' } },
                        row.title && React__default["default"].createElement(
                          Card__default["default"].Title,
                          null,
                          React__default["default"].createElement(
                            'a',
                            { href: _this2.page + '/' + get.get_1(row, 'url.current') },
                            row.title
                          )
                        ),
                        _this2.props.showPublished && row.published && React__default["default"].createElement(
                          Card__default["default"].Subtitle,
                          null,
                          moment.moment(row.published).format('MMMM DD, YYYY')
                        ),
                        _this2.props.showRecent && row.recent && row.recent.title && React__default["default"].createElement(
                          Card__default["default"].Subtitle,
                          null,
                          'Recent : ',
                          React__default["default"].createElement(
                            'a',
                            { href: 'view/' + row.recent.url.current },
                            row.recent.title
                          )
                        ),
                        row.summary && React__default["default"].createElement(
                          Card__default["default"].Text,
                          null,
                          React__default["default"].createElement(
                            'a',
                            { href: _this2.page + '/' + get.get_1(row, 'url.current') },
                            entities.clean_html_1(row.summary)
                          )
                        )
                      )
                    )
                  )
                )
              )
            ),
            main.main_43 && _this2.props.rightItems && (index + 1) % numberOfItemsBeforeAd === 0 && _this2.renderMobileAd(index, numberOfItemsBeforeAd)
          );
        })
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _this3 = this;

      var _props = this.props,
          columns = _props.columns,
          variant = _props.variant,
          autoScroll = _props.autoScroll,
          page = _props.page,
          _props$nextPagePostsC = _props.nextPagePostsCount,
          nextPagePostsCount = _props$nextPagePostsC === undefined ? 3 : _props$nextPagePostsC;


      return React__default["default"].createElement(
        'div',
        { className: 'contentDeck' },
        autoScroll ? React__default["default"].createElement(
          React__default["default"].Fragment,
          null,
          React__default["default"].createElement(
            index_es.InfiniteScroll,
            { dataLength: this.state.data.length, next: this.loadMore, hasMore: this.state.scrolling },
            React__default["default"].createElement(
              Container__default["default"],
              null,
              this.cardLoader(page, columns, variant)
            )
          ),
          React__default["default"].createElement(
            'noscript',
            null,
            this.renderManualPagination({ nextPagePostsCount: nextPagePostsCount })
          )
        ) : React__default["default"].createElement(
          React__default["default"].Fragment,
          null,
          React__default["default"].createElement(
            Container__default["default"],
            null,
            this.cardLoader(page, columns, variant)
          ),
          React__default["default"].createElement(
            'div',
            { style: { padding: '0px 10px' } },
            this.state.scrolling ? React__default["default"].createElement(
              'button',
              {
                style: { margin: 'auto', width: '100%' },
                onClick: function onClick(e) {
                  _this3.loadMore();
                } },
              'Load More'
            ) : React__default["default"].createElement(
              'p',
              { style: { textAlign: 'center' } },
              React__default["default"].createElement(
                'b',
                null,
                'End of data'
              )
            )
          ),
          React__default["default"].createElement(
            'noscript',
            null,
            this.renderManualPagination({ nextPagePostsCount: nextPagePostsCount })
          )
        )
      );
    }
  }]);

  return DeckQueue;
}(React__default["default"].Component);

var Queue = Router.withRouter(DeckQueue);

module.exports = Queue;
