'use strict';

var toConsumableArray = require('./toConsumableArray-d7797c2b.js');
var _extends = require('./extends-7c86182f.js');
var slicedToArray = require('./slicedToArray-067dd3bc.js');
var React = require('react');
var Router = require('next/router');
var index = require('./index-fc2f1ca2.js');
var index_es = require('./index.es-f3e47207.js');
var SeriesSlider = require('./SeriesSlider-ce3261cb.js');
var visibilitySensor = require('./visibility-sensor-eb2c5b69.js');
require('./_commonjsHelpers-06173234.js');
require('./core.get-iterator-method-5643aa10.js');
require('./_iter-detect-b1df62f0.js');
require('./_object-pie-083f2dd6.js');
require('./web.dom.iterable-d98303e0.js');
require('./events-1b438fe7.js');
require('prop-types');
require('./index-187c967e.js');
require('./index-eadd5035.js');
require('react-dom');
require('./smoothscroll-99df7f93.js');
require('./urlFor.js');
require('./index-efca863c.js');
require('./main-025fdc78.js');

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

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

var usePrevious = function usePrevious(value) {
  var ref = React.useRef();
  React.useEffect(function () {
    ref.current = value;
  });
  return ref.current;
};

var SeriesListingDeck = function SeriesListingDeck(props) {
  var data = props.data,
      client = props.client,
      query = props.query,
      params = props.params,
      parentIdentifier = props.identifier,
      initialCurrentPage = props.currentPage,
      pageview = props.pageview;

  var _useState = React.useState(params ? params.count : 0),
      _useState2 = slicedToArray._slicedToArray(_useState, 1),
      count = _useState2[0];

  var _useState3 = React.useState(true),
      _useState4 = slicedToArray._slicedToArray(_useState3, 2),
      scrolling = _useState4[0],
      setScrolling = _useState4[1];

  var _useState5 = React.useState(data.series),
      _useState6 = slicedToArray._slicedToArray(_useState5, 2),
      seriesData = _useState6[0],
      setSeriesData = _useState6[1];

  var _useState7 = React.useState(initialCurrentPage || 1),
      _useState8 = slicedToArray._slicedToArray(_useState7, 2),
      currentPage = _useState8[0],
      setCurrentPage = _useState8[1];

  var _useState9 = React.useState({
    from: params ? params.from : 0,
    to: params ? params.to : 0,
    page: 1
  }),
      _useState10 = slicedToArray._slicedToArray(_useState9, 2),
      values = _useState10[0],
      setValues = _useState10[1];

  var prevValues = usePrevious(values);

  var router = Router.useRouter();

  var loadMore = function loadMore() {
    setValues({
      page: values.page + 1,
      from: parseInt(values.from) + parseInt(count),
      to: parseInt(values.to) + parseInt(count)
    });
  };

  var changePageNumber = function changePageNumber(pageNumber, arrIndex, pageview) {
    if (pageNumber) {
      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)
      var index$1 = Number(arrIndex);
      var perPage = 6;

      pageNumber = Math.ceil((index$1 + 1) / perPage);

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

        setCurrentPage(pageNumber);
        if (path[0] !== '/') {
          path = '/' + path;
        }

        var newPath = pageNumber === 1 ? '' + path : '' + path + (queryString.length > 0 ? '&' : '?') + 'page=' + pageNumber;

        if (pageview) {
          pageview(newPath);
        }

        router.push(pathname, newPath, {
          shallow: true
        });
      }
    }
  };

  var loadData = function loadData(values, query, client, params, setSeriesData, setScrolling) {
    params = _extends._extends({}, params, {
      from: values.from,
      to: values.to
    });

    client.fetch(query, params).then(function (dataArr) {
      if (!dataArr.series) {
        dataArr.series = [];
      }

      dataArr.series = dataArr.series.map(function (item) {
        return _extends._extends({}, item, {
          pageNumber: values.page
        });
      });

      if (dataArr.series.length > 0) {
        setSeriesData(function (prevData) {
          var newArr = [].concat(toConsumableArray._toConsumableArray(prevData), toConsumableArray._toConsumableArray(dataArr.series));
          return newArr;
        });
        setScrolling(true);
      } else {
        var parentScroll = document.getElementsByClassName('infinite-scroll-component')[0];
        parentScroll.style.overflow = 'hidden';
        setScrolling(false);
      }
    });
  };

  React.useEffect(function () {
    if (prevValues) {
      if (values.page !== prevValues.page && values.from !== prevValues.from && values.to !== prevValues.from) {
        loadData(values, query, client, params, setSeriesData, setScrolling);
      }
    }
  }, [values, prevValues, query, client, params, setSeriesData, setScrolling]);

  React.useEffect(function () {
    if (seriesData.length < count) {
      var parentScroll = document.getElementsByClassName('infinite-scroll-component')[0];
      parentScroll.style.overflow = 'hidden';
      setScrolling(false);
    }
  }, [seriesData, setScrolling, count]);

  return React__default['default'].createElement(
    index_es.InfiniteScroll,
    { dataLength: seriesData && seriesData.length, next: function next() {
        return loadMore();
      }, hasMore: scrolling, scrollThreshold: 0.9 },
    React__default['default'].createElement(
      'div',
      null,
      seriesData && seriesData.length ? React__default['default'].createElement(
        'div',
        null,
        seriesData.map(function (series, index) {
          return React__default['default'].createElement(
            visibilitySensor.VisibilitySensor,
            {
              key: series._id ? series._id : index,
              partialVisibility: true,
              onChange: function onChange(isVisible) {
                isVisible && changePageNumber(currentPage, index, pageview);
              } },
            React__default['default'].createElement(
              'div',
              { className: 'mb-5', key: series.name },
              React__default['default'].createElement(
                'div',
                { style: { fontSize: '20px', fontWeight: 'bold', borderBottom: '1px solid #eee', margin: '0 .5rem', color: '373a3c' } },
                React__default['default'].createElement(
                  'a',
                  { href: '/' + parentIdentifier + '/' + series.identifier.current },
                  series.name
                )
              ),
              series.articles && series.articles.length == 0 && React__default['default'].createElement(
                'p',
                { className: 'mt-2 ml-2' },
                'Please check back for more content.'
              ),
              series.articles && series.articles.length > 0 && React__default['default'].createElement(SeriesSlider.SeriesSlider, _extends._extends({}, props, { dataset: series.articles, client: client }))
            )
          );
        })
      ) : React__default['default'].createElement(
        'div',
        null,
        React__default['default'].createElement(
          'h5',
          null,
          React__default['default'].createElement(
            'em',
            { className: 'pl-3' },
            'New content coming soon, please check back later.'
          )
        )
      )
    )
  );
};

module.exports = SeriesListingDeck;
