'use strict';

var stringify = require('./stringify-f7a37a8d.js');
var asyncToGenerator = require('./asyncToGenerator-77821af0.js');
var _extends = require('./extends-7c86182f.js');
var inherits = require('./inherits-de66ea16.js');
var React = require('react');
var index = require('./index-d2a6ef75.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 Spinner = require('react-bootstrap/Spinner');
var moment = require('./moment-aca40de1.js');
var Router = require('next/router');
var index$1 = require('./index-65621b6c.js');
var get = require('./get-5839e5b5.js');
var main = require('./main-6054981e.js');
var urlFor = require('./urlFor.js');
var entities = require('./entities-df1aed86.js');
var Pagination = require('./Pagination-6359861a.js');
require('./_commonjsHelpers-06173234.js');
require('./core.get-iterator-method-5643aa10.js');
require('./web.dom.iterable-d98303e0.js');
require('./_library-dd23b178.js');
require('./_iter-detect-b1df62f0.js');
require('./_object-pie-083f2dd6.js');
require('./_object-sap-d1978572.js');
require('./define-property-e8404b64.js');
require('./typeof-567e31ff.js');
require('./_is-array-54228b29.js');
require('./events-1b438fe7.js');
require('prop-types');
require('react-dom');
require('./isSymbol-03abbdf0.js');
require('./eq-5fc26c07.js');
require('./slicedToArray-067dd3bc.js');
require('./index-d48b231c.js');
require('react-bootstrap/Button');
require('./index.esm-d51c9ac6.js');
require('./iconBase-be4097c0.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 Spinner__default = /*#__PURE__*/_interopDefaultLegacy(Spinner);

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

  function DeckQueue() {
    var _ref,
        _this2 = this;

    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.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,
      prevData: _this.data,
      currentPage: _this.props.currentPage || 1,
      isDataLoading: false,
      itemsPerPage: _this.props.params ? _this.props.params.to - _this.props.params.from : 2
    }, _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.seoPagination = function (pageNumber) {
      var _this$props = _this.props,
          pageview = _this$props.pageview,
          router = _this$props.router;

      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 (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.handlePageChange = function () {
      var _ref2 = asyncToGenerator._asyncToGenerator( /*#__PURE__*/asyncToGenerator.regenerator.mark(function _callee(selectedPage) {
        var itemsPerPage, _this$props2, query, params, client, seoPaginate, start, newParams, newData;

        return asyncToGenerator.regenerator.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                itemsPerPage = _this.state.itemsPerPage;
                _this$props2 = _this.props, query = _this$props2.query, params = _this$props2.params, client = _this$props2.client, seoPaginate = _this$props2.seoPaginate;

                _this.setState({ isDataLoading: true, currentPage: selectedPage });
                seoPaginate && _this.seoPagination(selectedPage);
                index.lib_3.refresh();
                document.body.scrollTop = 0;
                document.documentElement.scrollTop = 0;
                start = (selectedPage - 1) * itemsPerPage;
                newParams = _extends._extends({}, params, {
                  from: start,
                  to: start + itemsPerPage
                });
                _context.prev = 9;
                _context.next = 12;
                return client.fetch(query, newParams);

              case 12:
                newData = _context.sent;

                if (_this.pointer && _this.pointerArray) newData = newData[_this.pointerArray][_this.pointer];
                if (newData && newData.length > 0) {
                  _this.setState({ isDataLoading: false, data: newData });
                }
                _context.next = 20;
                break;

              case 17:
                _context.prev = 17;
                _context.t0 = _context['catch'](9);

                console.error(_context.t0);

              case 20:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, _this2, [[9, 17]]);
      }));

      return function (_x) {
        return _ref2.apply(this, arguments);
      };
    }(), _temp), inherits._possibleConstructorReturn(_this, _ret);
  }

  inherits._createClass(DeckQueue, [{
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps, prevState) {
      if (stringify._JSON$stringify(this.state.prevData) !== stringify._JSON$stringify(prevState.prevData) && this.props.seoPaginate) {
        this.seoPagination(this.state.currentPage);
      }
    }
  }, {
    key: 'cardLoader',
    value: function cardLoader(_ref3) {
      var _this3 = this;

      var columns = _ref3.columns,
          variant = _ref3.variant;

      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) {
          // 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(
              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 || _this3.props.defaultImage) && React__default["default"].createElement(
                    Col__default["default"],
                    { md: 12, lg: 4 },
                    React__default["default"].createElement(
                      'a',
                      { href: _this3.page + '/' + get.get_1(row, 'url.current') },
                      React__default["default"].createElement(
                        index$1.LazyLoad,
                        { height: _this3.props.imageHeight },
                        React__default["default"].createElement(Card__default["default"].Img, { variant: 'top', src: _this3.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: _this3.page + '/' + get.get_1(row, 'url.current') },
                          row.title
                        )
                      ),
                      _this3.props.showPublished && row.published && React__default["default"].createElement(
                        Card__default["default"].Subtitle,
                        null,
                        moment.moment(row.published).format('MMMM DD, YYYY')
                      ),
                      _this3.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: _this3.page + '/' + get.get_1(row, 'url.current') },
                          entities.clean_html_1(row.summary)
                        )
                      )
                    )
                  )
                )
              )
            ),
            main.main_43 && _this3.props.rightItems && (index + 1) % numberOfItemsBeforeAd === 0 && _this3.renderMobileAd(index, numberOfItemsBeforeAd)
          );
        })
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          columns = _props.columns,
          variant = _props.variant,
          totalDataCount = _props.totalDataCount;
      var _state = this.state,
          data = _state.data,
          isDataLoading = _state.isDataLoading,
          itemsPerPage = _state.itemsPerPage,
          currentPage = _state.currentPage;

      return React__default["default"].createElement(
        'div',
        { className: 'contentDeck' },
        isDataLoading ? React__default["default"].createElement(
          'div',
          { className: 'd-flex justify-content-center', style: { marginTop: '100px' } },
          React__default["default"].createElement(
            Spinner__default["default"],
            { animation: 'border', role: 'status' },
            React__default["default"].createElement(
              'span',
              { className: 'sr-only' },
              'Loading...'
            )
          )
        ) : data && data.length > 0 ? React__default["default"].createElement(
          Container__default["default"],
          null,
          this.cardLoader({ columns: columns, variant: variant }),
          React__default["default"].createElement(
            'div',
            { className: 'pagination-wrapper' },
            React__default["default"].createElement(Pagination.Pagination, {
              pageCount: Math.ceil(totalDataCount / itemsPerPage),
              pageRangeDisplayed: main.main_43 ? 3 : 9,
              currentPage: currentPage,
              onPageChange: this.handlePageChange,
              needLargePaginateButtons: this.props.needLargePaginateButtons
            }),
            React__default["default"].createElement(
              'style',
              { jsx: 'true' },
              '\n                .pagination-wrapper {\n                  margin: 3rem 0 100px 0;\n                }\n              '
            )
          )
        ) : null
      );
    }
  }], [{
    key: 'getDerivedStateFromProps',
    value: function getDerivedStateFromProps(props, state) {
      if (stringify._JSON$stringify(props.dataRecord) !== stringify._JSON$stringify(state.prevData)) {
        return {
          data: props.dataRecord,
          prevData: props.dataRecord,
          currentPage: props.currentPage
        };
      }
      return null;
    }
  }]);

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

var QueuePaginated = Router.withRouter(DeckQueue);

module.exports = QueuePaginated;
