'use strict';

var stringify = require('./stringify-f7a37a8d.js');
var asyncToGenerator = require('./asyncToGenerator-65df6bf8.js');
var _extends = require('./extends-be0d85bc.js');
var toConsumableArray = require('./toConsumableArray-d7797c2b.js');
var inherits = require('./inherits-e47b5342.js');
var React = require('react');
var index = require('./index-fc2f1ca2.js');
var Container = require('react-bootstrap/Container');
var Spinner = require('react-bootstrap/Spinner');
var Router = require('next/router');
var lodash = require('./lodash-f0783643.js');
var main = require('./main-1ec1de84.js');
var ADlgInfeed = require('./ADlgInfeed-d88a0250.js');
var ADInfeed = require('./ADInfeed-3a68b356.js');
var Pagination = require('./Pagination-2a3d0103.js');
require('./_commonjsHelpers-06173234.js');
require('./core.get-iterator-method-5643aa10.js');
require('./web.dom.iterable-d98303e0.js');
require('./_library-dd23b178.js');
require('./_set-species-0c7864a2.js');
require('./_iter-detect-b1df62f0.js');
require('./_object-sap-d1978572.js');
require('./define-property-e8404b64.js');
require('./typeof-220bbf73.js');
require('./_is-array-54228b29.js');
require('./events-1b438fe7.js');
require('prop-types');
require('./slicedToArray-067dd3bc.js');
require('react-bootstrap/Card');
require('./AdSlot.js');
require('./debounce-d4a2369b.js');
require('./isSymbol-03abbdf0.js');
require('./toNumber-5e1fac58.js');
require('./Beam.js');
require('./Segment.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 Spinner__default = /*#__PURE__*/_interopDefaultLegacy(Spinner);

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.data = _this.props.dataRecord || [], _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.state = {
      isDataLoading: false,
      data: _this.data,
      prevData: _this.data,
      currentPage: _this.props.currentPage || 1,
      dataRemapped: !_this.props.showBI || !_this.props.brandInsightAd,
      itemsPerPage: _this.props.params ? _this.props.params.to - _this.props.params.from : 2,
      mobileView: false
    }, _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 (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 (_ref2) {
      var variant = _ref2.variant,
          brandInsightAd = _ref2.brandInsightAd,
          showBI = _ref2.showBI,
          lgInfeedAd = _ref2.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) {
          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(
              React__default['default'].Fragment,
              { key: index },
              React__default['default'].createElement(_this2.Deck, {
                data: row,
                currentPage: _this.state.currentPage,
                itemsPerPage: _this.state.itemsPerPage,
                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) {
          if (!row._type || !['lg-infeed', 'brandInsightAd'].includes(row._type)) {
            return React__default['default'].createElement(
              React__default['default'].Fragment,
              { key: index },
              React__default['default'].createElement(_this2.Deck, {
                data: row,
                currentPage: _this.state.currentPage,
                itemsPerPage: _this.state.itemsPerPage,
                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.handlePageChange = function () {
      var _ref3 = asyncToGenerator._asyncToGenerator( /*#__PURE__*/asyncToGenerator.regenerator.mark(function _callee(selectedPage) {
        var itemsPerPage, _this$props2, query, params, client, dataHandler, seoPaginate, start, newParams, dataHandlerPromise, 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, dataHandler = _this$props2.dataHandler, 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
                });
                dataHandlerPromise = null;

                if (dataHandler) {
                  dataHandlerPromise = new asyncToGenerator._Promise(function (resolve, reject) {
                    try {
                      var result = dataHandler(newParams);
                      resolve(result);
                    } catch (e) {
                      reject(e);
                    }
                  });
                }

                _context.prev = 11;

                if (!dataHandlerPromise) {
                  _context.next = 18;
                  break;
                }

                _context.next = 15;
                return dataHandlerPromise;

              case 15:
                _context.t0 = _context.sent;
                _context.next = 21;
                break;

              case 18:
                _context.next = 20;
                return client.fetch(query, newParams);

              case 20:
                _context.t0 = _context.sent;

              case 21:
                newData = _context.t0;

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

              case 26:
                _context.prev = 26;
                _context.t1 = _context['catch'](11);

                console.error(_context.t1);

              case 29:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, _this2, [[11, 26]]);
      }));

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

  inherits._createClass(MasterDeck, [{
    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);
      }
      // 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: 'render',
    value: function render() {
      //  Setting default value for 'showBI' and 'lgInfeedAd'
      var _props = this.props,
          variant = _props.variant,
          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,
          totalDataCount = _props.totalDataCount;
      var _state = this.state,
          data = _state.data,
          itemsPerPage = _state.itemsPerPage,
          currentPage = _state.currentPage,
          isDataLoading = _state.isDataLoading;

      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({ variant: variant, brandInsightAd: brandInsightAd, showBI: showBI, lgInfeedAd: lgInfeedAd }),
          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;
    }
    //  Passing 'brandInsightAd','showBI' and 'lgInfeedAd'

  }]);

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

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

module.exports = MasterDeck$1;
