'use strict';

var _extends = require('./extends-29bdbc6d.js');
var inherits = require('./inherits-c2065b95.js');
var React = require('react');
var index = require('./index-fc2f1ca2.js');
var Container = require('react-bootstrap/Container');
var visibilitySensor = require('./visibility-sensor-eb2c5b69.js');
var index_esm = require('./index.esm-974f47d9.js');
var moment = require('./moment-aca40de1.js');
var Router = require('next/router');
var YoutubeGroup = require('./YoutubeGroup.js');
var debounce = require('./debounce-d4a2369b.js');
var index_es = require('./index.es-f3e47207.js');
require('./_commonjsHelpers-06173234.js');
require('./_to-object-6de10e57.js');
require('./_object-pie-083f2dd6.js');
require('./es6.string.iterator-c2573ffd.js');
require('./_object-sap-a175b4a9.js');
require('./define-property-c88be878.js');
require('./typeof-88a668c5.js');
require('./web.dom.iterable-46657b5c.js');
require('./_is-array-6128bd56.js');
require('./_library-dd23b178.js');
require('./events-1b438fe7.js');
require('prop-types');
require('react-dom');
require('./iconBase-68959171.js');
require('./slicedToArray-5d1bc3b3.js');
require('./core.get-iterator-method-f474eacc.js');
require('./index-187c967e.js');
require('./index-eadd5035.js');
require('./smoothscroll-99df7f93.js');
require('./urlFor.js');
require('./index-efca863c.js');
require('./main-025fdc78.js');
require('./isSymbol-03abbdf0.js');
require('./toNumber-5e1fac58.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 VideoSeriesListing = function (_React$Component) {
  inherits._inherits(VideoSeriesListing, _React$Component);

  function VideoSeriesListing() {
    var _ref;

    var _temp, _this, _ret;

    inherits._classCallCheck(this, VideoSeriesListing);

    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 = VideoSeriesListing.__proto__ || inherits._Object$getPrototypeOf(VideoSeriesListing)).call.apply(_ref, [this].concat(args))), _this), _this.page = _this.props.page, _this.mapping = _this.props.mapping, _this.data = _this.props.dataRecord, _this.query = _this.props.query, _this.params = _this.props.params, _this.today = moment.moment().utc().format(), _this.dataArr = [_this.data], _this.defaultImage = _this.props.defaultImage ? _this.props.defaultImage : '/placeholder.jpg', _this.state = {
      data: _this.dataArr.map(function (item) {
        var tempObj = item.map(function (arrItem) {
          if (arrItem.body) {
            var filteredBody = arrItem.body.map(function (item) {
              if (item._type === 'youtubeGallery') {
                var innerObj = item;
                var filteredArticles = innerObj.videos.filter(function (video) {
                  if ((video.is_visible === true || !video.hasOwnProperty('is_visible')) && (_this.today >= video.published || !video.hasOwnProperty('published'))) {
                    return video;
                  }
                });
                innerObj.videos = filteredArticles;
                return innerObj;
              } else {
                return item;
              }
            });

            arrItem.body = filteredBody;
          }
          return arrItem;
        });
        return tempObj;
      }),
      per: _this.params ? _this.params.itemsPerPage : 2,
      page: _this.props.currentPage || 1,
      from: _this.params ? _this.params.from : 0,
      to: _this.params ? _this.params.to : 2,
      total_pages: null,
      scrolling: true,
      query: _this.query,
      currentPage: _this.props.currentPage || 1
    }, _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;
          _this$state.data;
          var query = _this$state.query,
          page = _this$state.page;
      var client = _this.props.client;
      //this.changePageNumber(page)

      var params = _extends._extends({}, _this.params, { from: from, to: to
        // const queryUpdated = query.replace('$from', params.from).replace('$to', params.to)
        // const query = '*[_type == "article" && defined(title) && defined(thumbnail)][$from...$to] { title, summary, thumbnail { asset-> }, url }'
      });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) {
            var newDataArr = _this.state.data;
            newDataArr.push(dataArr);
            return {
              data: newDataArr,
              scrolling: true
            };
          } else {
            return {
              scrolling: false
            };
          }
        });
      });
    }, _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 + (path.includes('?') ? '&page=' + pageNumber : '?page=' + pageNumber);

            if (pageview) {
              pageview(newPath);
            }

            router.push(pathname, newPath, {
              shallow: true
            });
          });
        }
      }
    }, _this.renderManualPagination = function () {
      var currentPage = _this.state.currentPage;

      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'
        ),
        React__default['default'].createElement(
          'a',
          { href: '?page=' + (currentPage + 1) },
          'Next >>'
        )
      );
    }, _this.renderSeries = function (seriesData) {
      var itemCounter = 0;

      return React__default['default'].createElement(
        'div',
        null,
        seriesData && seriesData.map(function (docSeries, index) {
          if (docSeries.body && docSeries.body.length > 0 && docSeries.body[0].videos) {
            docSeries.body[0].videos.map(function (singleVideo, indexInner) {
              singleVideo.link = '/view/' + docSeries.url.current + '?seriesVid=' + (indexInner + 1);
            });
          }

          return React__default['default'].createElement(
            'div',
            { key: index, style: { marginBottom: '2rem' }, counter: itemCounter++ },
            React__default['default'].createElement(
              'div',
              {
                className: 'video-title-banner',
                style: { fontWeight: 'bold', color: 'var(--primary)', padding: '.25rem 0', fontSize: '1.25rem', borderBottom: '1px solid #d4a64d' } },
              React__default['default'].createElement(
                'a',
                { href: '/' + _this.props.page + '/' + docSeries.url.current },
                docSeries.title,
                React__default['default'].createElement(
                  'span',
                  { style: { fontSize: '.9rem', color: 'grey', marginLeft: '1rem', transform: 'translateY(-2px)' } },
                  React__default['default'].createElement(index_esm.IoIosArrowForward, null)
                )
              )
            ),
            docSeries.body && docSeries.body.length > 0 && docSeries.body[0].videos ? React__default['default'].createElement(YoutubeGroup, _extends._extends({ displayEpisodeNumber: true, key: index, dataset: docSeries.body[0].videos }, _this.props)) : React__default['default'].createElement(
              'p',
              null,
              'No Video Found.'
            )
          );
        })
      );
    }, _temp), inherits._possibleConstructorReturn(_this, _ret);
  }

  inherits._createClass(VideoSeriesListing, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      // console.log(this.state)
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props$autoScroll = this.props.autoScroll,
          autoScroll = _props$autoScroll === undefined ? true : _props$autoScroll;


      if (autoScroll) {
        return React__default['default'].createElement(
          React__default['default'].Fragment,
          null,
          this.state.data.length >= 1 && this.state.data[0].length > 0 ?
          //Check if any Video Groups available
          React__default['default'].createElement(
            index_es.InfiniteScroll,
            { dataLength: this.state.data.length, next: this.loadMore, hasMore: this.state.scrolling, scrollThreshold: 0.8 },
            React__default['default'].createElement(
              Container__default['default'],
              null,
              this.state.data && this.state.data.map(function (series, index) {
                var page = series && series.length > 0 && series[0].pageNumber !== 1 ? series[0].pageNumber : 1;

                return React__default['default'].createElement(
                  React__default['default'].Fragment,
                  { key: index },
                  React__default['default'].createElement(
                    visibilitySensor.VisibilitySensor,
                    {
                      onChange: function onChange(isVisible) {
                        isVisible && _this2.changePageNumber(page);
                      } },
                    React__default['default'].createElement('div', { className: 'visibility-sensor', style: { minHeight: '.25rem' } })
                  ),
                  React__default['default'].createElement(
                    'div',
                    null,
                    _this2.renderSeries(series)
                  )
                );
              }),
              React__default['default'].createElement(
                'noscript',
                null,
                this.renderManualPagination()
              )
            )
          ) : React__default['default'].createElement(
            'div',
            { style: { marginTop: '10px' } },
            React__default['default'].createElement(
              'h5',
              null,
              React__default['default'].createElement(
                'em',
                null,
                'New content coming soon, please check back later.'
              )
            )
          )
        );
      }
      if (!autoScroll) {
        return React__default['default'].createElement(
          React__default['default'].Fragment,
          null,
          this.state.data.length >= 1 && this.state.data[0].length > 0 ?
          //Check if any Video Groups available
          React__default['default'].createElement(
            Container__default['default'],
            null,
            this.state.data && this.state.data.map(function (series, index) {
              var page = series && series.length > 0 && series[0].pageNumber !== 1 ? series[0].pageNumber : 1;

              return React__default['default'].createElement(
                React__default['default'].Fragment,
                { key: index },
                React__default['default'].createElement(
                  visibilitySensor.VisibilitySensor,
                  {
                    onChange: function onChange(isVisible) {
                      isVisible && _this2.changePageNumber(page);
                    } },
                  React__default['default'].createElement('div', { className: 'visibility-sensor', style: { minHeight: '.25rem' } })
                ),
                React__default['default'].createElement(
                  'div',
                  null,
                  _this2.renderSeries(series)
                ),
                _this2.state.scrolling ? React__default['default'].createElement(
                  'button',
                  {
                    className: 'btn',
                    style: {
                      margin: '0 auto 2rem',
                      display: 'block',
                      fontSize: '18px',
                      padding: '.5rem 1.5rem',
                      boxShadow: '1px 2px 4px 4px rgba(0,0,0,.15)',
                      background: 'var(--primary)',
                      color: '#fff',
                      borderRadius: '5px'
                    },
                    onClick: function onClick(e) {
                      e.target.style.display = 'none';
                      _this2.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,
                  _this2.renderManualPagination()
                )
              );
            })
          ) : React__default['default'].createElement(
            'div',
            { style: { marginTop: '10px' } },
            React__default['default'].createElement(
              'h5',
              null,
              React__default['default'].createElement(
                'em',
                null,
                'New content coming soon, please check back later.'
              )
            )
          )
        );
      }
    }
  }]);

  return VideoSeriesListing;
}(React__default['default'].Component);

var VideoSeriesListing$1 = Router.withRouter(VideoSeriesListing);

module.exports = VideoSeriesListing$1;
