'use strict';

var toConsumableArray = require('./toConsumableArray-d7797c2b.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-fc2f1ca2.js');
var Container = require('react-bootstrap/Container');
require('react-bootstrap/Row');
require('react-bootstrap/Col');
require('react-bootstrap/Card');
require('./moment-aca40de1.js');
var Router = require('next/router');
var lodash = require('./lodash-f0783643.js');
var debounce = require('./debounce-d4a2369b.js');
var index_es = require('./index.es-f3e47207.js');
var visibilitySensor = require('./visibility-sensor-eb2c5b69.js');
require('./slicedToArray-067dd3bc.js');
require('./index-d48b231c.js');
var ADlgInfeed = require('./ADlgInfeed-24d739f6.js');
var ADInfeed = require('./ADInfeed-44d43b8a.js');
require('./main-f1c77adb.js');
require('./_commonjsHelpers-06173234.js');
require('./core.get-iterator-method-5643aa10.js');
require('./_iter-detect-b1df62f0.js');
require('./web.dom.iterable-d98303e0.js');
require('./_library-dd23b178.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('./isSymbol-03abbdf0.js');
require('./toNumber-5e1fac58.js');
require('react-dom');
require('./AdSlot.js');
require('./Beam.js');
require('./stringify-f7a37a8d.js');
require('./Segment.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 MasterDeck = function (_React$Component) {
  inherits._inherits(MasterDeck, _React$Component);

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

    var _temp, _this, _ret;

    inherits._classCallCheck(this, MasterDeck);

    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 = MasterDeck.__proto__ || inherits._Object$getPrototypeOf(MasterDeck)).call.apply(_ref, [this].concat(args))), _this), _this.Deck = _this.props.deck, _this.variant = _this.props.variant, _this.mapping = _this.props.mapping, _this.data = _this.props.dataRecord || [], _this.query = _this.props.query, _this.params = _this.props.params, _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.rightItems = _this.props.rightItems ? _this.props.rightItems : false, _this.isSeriesLanding = _this.props.isSeriesLanding ? _this.props.isSeriesLanding : false, _this.client = _this.props.client, _this.state = {
      data: _this.data,
      dataKeptToCompareNewDatarecord: _this.data,
      per: _this.params ? _this.params.to : 2,
      page: _this.props.currentPage || 1,
      from: _this.params ? _this.params.from : 0,
      to: _this.params ? _this.params.to : 2,
      total_pages: null,
      scrolling: false,
      query: _this.query,
      currentPage: _this.props.currentPage || 1,
      dataRemapped: !_this.props.showBI || !_this.props.brandInsightAd,
      lastDataSize: _this.data ? _this.data.length : 0,
      itemsPerPage: _this.params ? _this.params.to - _this.params.from : 2,
      mobileView: false
    }, _this.loadMore = debounce.debounce_1(function () {
      _this.setState(function (state) {
        var page = state.page,
            from = state.from,
            to = state.to,
            itemsPerPage = state.itemsPerPage;

        return {
          page: page + 1,
          from: from + itemsPerPage,
          to: to + itemsPerPage
        };
      }, _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 _this$props = _this.props,
          client = _this$props.client,
          dataHandler = _this$props.dataHandler;


      var params = _extends._extends({}, _this.props.params, { from: from, to: to + 1 });

      if (dataHandler) {
        var dataHandlerPromise = new asyncToGenerator._Promise(function (resolve, reject) {
          try {
            var result = dataHandler(params);
            resolve(result);
          } catch (e) {
            reject(e);
          }
        });
        dataHandlerPromise.then(function (dataArr) {
          _this.loadDataFinished(data, dataArr, page);
        });
      } else {
        client.fetch(query, params).then(function (dataArr) {
          _this.loadDataFinished(data, dataArr, page);
        });
      }
    }, _this.loadDataFinished = function (data, dataArr, page) {
      if (_this.pointer && _this.pointerArray) {
        var pointer = _this.pointer;
        dataArr = dataArr[_this.pointerArray][pointer];
      }

      if (dataArr && dataArr.length > 0) {
        var itemsPerPage = _this.state.itemsPerPage;

        var scrolling = dataArr.length === itemsPerPage + 1;
        dataArr = dataArr.slice(0, itemsPerPage).map(function (item) {
          return _extends._extends({}, item, {
            pageNumber: page
          });
        });

        _this.setState({
          data: [].concat(toConsumableArray._toConsumableArray(data), toConsumableArray._toConsumableArray(dataArr)),
          lastDataSize: dataArr.length,
          scrolling: scrolling
        });
      } else {
        _this.setState({
          scrolling: false,
          lastDataSize: 0
        });
      }
    }, _this.checkMoreDataAvailable = function () {
      var _this$state2 = _this.state,
          from = _this$state2.from,
          itemsPerPage = _this$state2.itemsPerPage,
          query = _this$state2.query;
      var _this$props2 = _this.props,
          client = _this$props2.client,
          dataHandler = _this$props2.dataHandler;

      var params = _extends._extends({}, _this.props.params, { from: from + itemsPerPage, to: from + itemsPerPage + 1 });
      if (dataHandler) {
        var dataHandlerPromise = new asyncToGenerator._Promise(function (resolve, reject) {
          try {
            var result = dataHandler(params);
            resolve(result);
          } catch (e) {
            reject(e);
          }
        });
        dataHandlerPromise.then(function (dataArr) {
          if (dataArr && dataArr.length > 0) _this.setState({ scrolling: true });else _this.setState({ scrolling: false });
        });
      } else {
        client.fetch(query, params).then(function (dataArr) {
          if (dataArr && dataArr.length > 0) _this.setState({ scrolling: true });else _this.setState({ scrolling: false });
        });
      }
    }, _this.changePageNumber = function (pageNumber) {
      var _this$props3 = _this.props,
          seoPaginate = _this$props3.seoPaginate,
          pageview = _this$props3.pageview,
          router = _this$props3.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 (window.location.href.includes('?')) {
              if (window.location.href.includes('?page')) {
                newPath = pageNumber === 1 ? '' + path : path + '?page=' + pageNumber;
              } else {
                newPath = pageNumber === 1 ? '' + path : path + '&page=' + pageNumber;
              }
            }

            // please leave this for later debug purpose : Yong Jun.
            /* console.log('page change reported', {
              currentPage: currentPage,
              pageNumber: pageNumber,
              pathname: pathname,
              path: path,
              newPath: newPath,
              firstPage: pageNumber === 1,
              queryString: queryString
            }) */

            if (pageview) {
              pageview(newPath);
            }

            router.push(pathname, newPath, {
              shallow: true
            });
          });
        }
      }
    }, _this.cardLoader = function (page, columns, variant, brandInsightAd, showBI, lgInfeedAd) {
      var numberOfItemsBeforeAd = 6;
      var data = _this.state.data;
      var insertBrandInsightAd = function insertBrandInsightAd(arr, index, newElement) {
        return [].concat(toConsumableArray._toConsumableArray(arr.slice(0, index)), [newElement], toConsumableArray._toConsumableArray(arr.slice(index)));
      };
      //  Need to pass flag "lgInfeedAd={true}" along with brandInsightAd from site level for large infeed-ad to render
      //  Checking lgInfeedAd flag in desktop view ( window >= 1400px ).
      //  Integrating large infeed AD
      if (lgInfeedAd && brandInsightAd && typeof window !== 'undefined' && window.innerWidth >= 1400) {
        var lgInfeed = {
          _type: 'lg-infeed',
          adUnit: brandInsightAd.adUnit,
          className: 'lg-infeed',
          networkID: brandInsightAd.networkID,
          sizes: [728, 90],
          sizeMapping: [{
            viewport: [1400, 0],
            sizes: [[728, 90]]
          }, { viewport: [0, 0], sizes: [] }],
          targeting: {
            content_placement: brandInsightAd.targeting.content_placement,
            document_url: brandInsightAd.targeting.document_url,
            document_group: brandInsightAd.targeting.document_group,
            rootDocumentGroup: brandInsightAd.targeting.rootDocumentGroup
          },
          /* Passing refresh flag */
          refreshFlag: brandInsightAd.refreshFlag ? brandInsightAd.refreshFlag : false
        };

        var chunks = lodash.lodash.chunk(data, 6).map(function (chunk) {
          var set = lodash.lodash.chunk(chunk, 2);
          for (var i = 0; i < set.length; i++) {
            if (i !== set.length - 1) {
              set[i].push(lgInfeed);
            }
          }
          return lodash.lodash.flattenDeep(set);
        });
        data = lodash.lodash.flatten(chunks);
        !_this.state.dataRemapped && _this.setState({ dataRemapped: true }); // To detect if appending of insights ads are completed
      }

      //  Integrating infeed AD
      if (showBI && brandInsightAd) {
        //  Checking lgInfeedAd flag in desktop view ( window >= 1400px ).
        if (lgInfeedAd && typeof window !== 'undefined' && window.innerWidth >= 1400) brandInsightAd.interval = 8;
        var pos = 0;
        for (var i = 1; pos < data.length; i++) {
          var inFeedAd = {
            adUnit: brandInsightAd.adUnit,
            className: brandInsightAd.className,
            networkID: brandInsightAd.networkID,
            sizes: brandInsightAd.sizes,
            slotId: brandInsightAd.slotId + '_' + i,
            targeting: {
              pos: 'infeed',
              content_placement: brandInsightAd.targeting.content_placement,
              document_url: brandInsightAd.targeting.document_url,
              document_group: brandInsightAd.targeting.document_group,
              rootDocumentGroup: brandInsightAd.targeting.rootDocumentGroup

            },
            _type: 'brandInsightAd',
            /* Passing refresh flag */
            refreshFlag: brandInsightAd.refreshFlag ? brandInsightAd.refreshFlag : false
          };

          data = insertBrandInsightAd(data, pos, inFeedAd);
          pos += brandInsightAd.interval + 1;
        }
      }

      // 'index' was including the indexes for infeed ads along with article count making the page number change before it reaches last article.
      data = data.map(function (ele, i) {
        if (ele._type === 'lg-infeed') {
          //  Setting pos as top2 for the first occurence of large infeed ad
          // const pos = data.indexOf(data.find((d) => d._type === 'lg-infeed')) === i ? 'top2' : `lg-infeed_${i}`
          return _extends._extends({}, ele, { slotId: 'lg-infeed_' + i, targeting: _extends._extends({}, ele.targeting, { pos: 'lg-infeed' }) });
        } else {
          return ele;
        }
      });

      return React__default['default'].createElement(
        'div',
        null,
        data && _this.state.dataRemapped && data.length > 0 ? // If JS enabled and Data remapped with ads
        data.map(function (row, index) {
          var pageNumber = row.pageNumber || _this.state.page;

          if (row._type === 'lg-infeed' && row.adUnit) {
            return React__default['default'].createElement(ADlgInfeed.ADlgInfeed, _extends._extends({ index: index }, row));
            //  Returning view for infeed Ad
          } else if (row._type === 'brandInsightAd' && row.adUnit) {
            return React__default['default'].createElement(ADInfeed.ADInfeed, { index: index, infeedAd: row });
          } else if (!row._type || !['lg-infeed', 'brandInsightAd'].includes(row._type)) {
            //  Returning view for articles
            return React__default['default'].createElement(
              visibilitySensor.VisibilitySensor,
              {
                key: row._id ? row._id : index,
                onChange: function onChange(isVisible) {
                  isVisible && _this.changePageNumber(pageNumber);
                } },
              React__default['default'].createElement(
                React__default['default'].Fragment,
                { key: index },
                React__default['default'].createElement(_this2.Deck, { data: row, variant: variant, index: index, client: _this.props.client, defaultImage: _this.defaultImage, isSeriesLanding: _this.isSeriesLanding }),
                _this.state.mobileView && _this.rightItems && (index + 1) % numberOfItemsBeforeAd === 0 && React__default['default'].createElement(
                  'div',
                  { className: 'ad-container', style: { margin: '0 auto' } },
                  _this.renderMobileAd(index, numberOfItemsBeforeAd, _this.rightItems)
                )
              )
            );
          } else {
            return null;
          }
        }) : data && data.length > 0 ? //For Javascript Disabled Cases. data is not remapped if JS is disabled.
        data.map(function (row, index) {
          var pageNumber = row.pageNumber || _this.state.page;
          if (!row._type || !['lg-infeed', 'brandInsightAd'].includes(row._type)) {
            return React__default['default'].createElement(
              visibilitySensor.VisibilitySensor,
              {
                key: row._id ? row._id : index,
                onChange: function onChange(isVisible) {
                  isVisible && _this.changePageNumber(pageNumber);
                } },
              React__default['default'].createElement(
                React__default['default'].Fragment,
                { key: index },
                React__default['default'].createElement(_this2.Deck, { data: row, variant: variant, index: index, client: _this.props.client, defaultImage: _this.defaultImage, isSeriesLanding: _this.isSeriesLanding })
              )
            );
          }
        }) : React__default['default'].createElement(
          'div',
          null,
          React__default['default'].createElement(
            'em',
            null,
            'New content coming soon, please check back later.'
          )
        )
      );
    }, _this.renderMobileAd = function (index, numberOfItemsBeforeAd, rightItems) {
      var i = ((index + 1) / numberOfItemsBeforeAd - 1) % rightItems.length;
      return React__default['default'].createElement(
        'div',
        { className: 'ad-container', style: { display: 'flex', flex: '1 0 auto', width: '100%', textAlign: 'center', marginBottom: '2rem' } },
        rightItems[i].component
      );
    }, _this.renderManualPagination = function () {
      var _this$state3 = _this.state,
          currentPage = _this$state3.currentPage,
          itemsPerPage = _this$state3.itemsPerPage,
          lastDataSize = _this$state3.lastDataSize;

      console.log('lastDataSize:', lastDataSize);
      console.log('itemsPerPage:', itemsPerPage);
      if (lastDataSize < itemsPerPage) {
        return null;
      }

      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 >>'
        )
      );
    }, _temp), inherits._possibleConstructorReturn(_this, _ret);
  }

  inherits._createClass(MasterDeck, [{
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps, prevState) {
      if (this.state.dataKeptToCompareNewDatarecord !== this.props.dataRecord) {
        // eslint-disable-next-line react/no-did-update-set-state
        this.setState({
          data: this.props.dataRecord,
          dataKeptToCompareNewDatarecord: this.props.dataRecord,
          per: this.props.params ? this.props.params.to : 2,
          page: 1,
          from: this.props.params ? this.props.params.from : 0,
          to: this.props.params ? this.props.params.to : 2,
          total_pages: null,
          scrolling: true,
          query: this.props.query,
          lastDataSize: this.props.dataRecord ? this.props.dataRecord.length : 0
        });
      }
      // set dataRemap to true as there are no infeed or BI ads or window width is less than limit
      if (typeof window !== 'undefined' && (!this.props.lgInfeedAd || !this.props.brandInsightAd || window.innerWidth < 1400) && !this.state.dataRemapped) {
        !this.state.dataRemapped && this.setState({ dataRemapped: true });
      }

      if (typeof window !== 'undefined' && window.innerWidth <= 1191) {
        !this.state.mobileView && this.setState({ mobileView: true });
      }
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      var _state = this.state,
          data = _state.data,
          itemsPerPage = _state.itemsPerPage;

      if (!(data.length < itemsPerPage)) this.checkMoreDataAvailable();
    }
    //  Passing 'brandInsightAd','showBI' and 'lgInfeedAd'

  }, {
    key: 'render',
    value: function render() {
      var _this3 = this;

      //  Setting default value for 'showBI' and 'lgInfeedAd'
      var _props = this.props,
          columns = _props.columns,
          variant = _props.variant,
          autoScroll = _props.autoScroll,
          page = _props.page,
          brandInsightAd = _props.brandInsightAd,
          _props$showBI = _props.showBI,
          showBI = _props$showBI === undefined ? false : _props$showBI,
          _props$lgInfeedAd = _props.lgInfeedAd,
          lgInfeedAd = _props$lgInfeedAd === undefined ? false : _props$lgInfeedAd;

      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, scrollThreshold: 0.9 },
            React__default['default'].createElement(
              Container__default['default'],
              null,
              this.cardLoader(page, columns, variant, brandInsightAd, showBI, lgInfeedAd)
            )
          ),
          React__default['default'].createElement(
            'noscript',
            null,
            this.renderManualPagination()
          )
        ) : React__default['default'].createElement(
          React__default['default'].Fragment,
          null,
          React__default['default'].createElement(
            Container__default['default'],
            null,
            this.cardLoader(page, columns, variant, brandInsightAd, showBI, lgInfeedAd)
          ),
          React__default['default'].createElement(
            'div',
            { style: { padding: '0px 10px' } },
            this.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) {
                  _this3.loadMore();
                } },
              'Load More'
            )
          ),
          React__default['default'].createElement(
            'noscript',
            null,
            this.renderManualPagination()
          )
        )
      );
    }
  }]);

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

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

module.exports = MasterDeck$1;
