'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

require('./_commonjsHelpers-06173234.js');
require('./_to-object-329a650b.js');
require('./es6.string.iterator-cc0bbaa4.js');
require('./_library-dd23b178.js');
require('./_iter-detect-60b2f026.js');
var toConsumableArray = require('./toConsumableArray-9a3476fe.js');
require('./core.get-iterator-method-f62321d4.js');
require('./_object-pie-68c5bcbc.js');
var _extends = require('./extends-60837c34.js');
require('./web.dom.iterable-a0e279c1.js');
var React = require('react');
var React__default = _interopDefault(React);
var index = require('./index-fa8ed292.js');
require('prop-types');
require('./moment-575fe24c.js');
var Router = require('next/router');
var Router__default = _interopDefault(Router);
require('./isSymbol-04666465.js');
var debounce = require('./debounce-eb287781.js');
var index_es = require('./index.es-9110add6.js');
require('react-dom');
var visibilitySensor = require('./visibility-sensor-0c45a583.js');
var main = require('./main-a4cb15bb.js');
var slicedToArray = require('./slicedToArray-8f385299.js');
var asyncToGenerator = require('./asyncToGenerator-533d476a.js');
require('./_set-species-f92c67c5.js');
var reactBootstrap = require('react-bootstrap');

var corsProxy = 'https://cors-anywhere.herokuapp.com/';
var itemsPerPage = 10;

var CMEDeck = function CMEDeck(_ref) {
  var getData = function () {
    var _ref2 = asyncToGenerator._asyncToGenerator( /*#__PURE__*/asyncToGenerator.regenerator.mark(function _callee(params) {
      var form, response, result, regex, newData;
      return asyncToGenerator.regenerator.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              form = new FormData();

              form.append('doc', 'per');
              form.append('from', params.from);
              form.append('limit', params.limit);
              form.append('keyword', keywords);
              _context.prev = 5;
              _context.next = 8;
              return fetch(corsProxy + 'http://vaccine.mjhassoc.com/doc_loader.php', {
                method: 'POST',
                body: form
              });

            case 8:
              response = _context.sent;
              _context.next = 11;
              return response.json();

            case 11:
              result = _context.sent;
              regex = /(&trade;)|(&reg;)|(&ndash;)|(&amp;)/gim;


              if (result && result.length > 0) {
                newData = result.map(function (activity) {
                  var entities = {
                    '&trade;': '\u2122',
                    '&reg;': '\xAE',
                    '&ndash;': '\u2013',
                    '&amp;': '&'
                  };

                  return _extends._extends({}, activity, {
                    title: activity.title.replace(regex, function (match) {
                      return entities[match];
                    }),
                    href: 'https://www.gotoper.com/' + activity.get1 + '/' + activity.get2 + '/' + activity.doc,
                    pageNumber: currentPage
                  });
                });

                setIsLoading(false);
                newData.length === itemsPerPage ? setScrolling(true) : setScrolling(false);
                setData(function (prevData) {
                  return [].concat(toConsumableArray._toConsumableArray(prevData), toConsumableArray._toConsumableArray(newData));
                });
              } else {
                setScrolling(false);
              }
              _context.next = 19;
              break;

            case 16:
              _context.prev = 16;
              _context.t0 = _context['catch'](5);

              console.log(_context.t0);

            case 19:
            case 'end':
              return _context.stop();
          }
        }
      }, _callee, this, [[5, 16]]);
    }));

    return function getData(_x) {
      return _ref2.apply(this, arguments);
    };
  }();

  var _ref$autoScroll = _ref.autoScroll,
      autoScroll = _ref$autoScroll === undefined ? true : _ref$autoScroll,
      _ref$variant = _ref.variant,
      variant = _ref$variant === undefined ? 'left' : _ref$variant,
      rightItems = _ref.rightItems,
      _ref$seoPaginate = _ref.seoPaginate,
      seoPaginate = _ref$seoPaginate === undefined ? true : _ref$seoPaginate,
      pageview = _ref.pageview,
      _ref$keywords = _ref.keywords,
      keywords = _ref$keywords === undefined ? '' : _ref$keywords;

  var router = Router.useRouter();

  var _useState = React.useState(true),
      _useState2 = slicedToArray._slicedToArray(_useState, 2),
      isLoading = _useState2[0],
      setIsLoading = _useState2[1];

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

  var _useState5 = React.useState(router && router.query && router.query.page ? parseInt(router.query.page) : 1),
      _useState6 = slicedToArray._slicedToArray(_useState5, 2),
      currentPage = _useState6[0],
      setCurrentPage = _useState6[1];

  var _useState7 = React.useState([]),
      _useState8 = slicedToArray._slicedToArray(_useState7, 2),
      data = _useState8[0],
      setData = _useState8[1];

  var _useState9 = React.useState(router && router.query && router.query.page ? (parseInt(router.query.page) - 1) * itemsPerPage : 0),
      _useState10 = slicedToArray._slicedToArray(_useState9, 2),
      from = _useState10[0],
      setFrom = _useState10[1];

  var currentPageRef = React.useRef(currentPage);
  var fromeRef = React.useRef(from);

  React.useEffect(function () {
    // load initial data
    getData({ from: from, limit: itemsPerPage });
  }, []);

  var changePageNumber = function changePageNumber(pageNumber) {
    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 (currentPageRef.current !== pageNumber) {
        index.lib_3.refresh();

        currentPageRef.current = pageNumber;
        if (path[0] !== '/') {
          path = '/' + path;
        }
        var newPath = pageNumber === 1 ? '' + path : path + '?page=' + pageNumber;

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

  var loadMore = debounce.debounce_1(function () {
    setFrom(function (prevFrom) {
      return prevFrom + itemsPerPage;
    });
    setCurrentPage(function (prevCurrentPage) {
      return prevCurrentPage + 1;
    });
  }, 0);

  React.useEffect(function () {
    if (currentPageRef.current !== currentPage && fromeRef.current !== from) {
      fromeRef.current = from;
      getData({ from: from, limit: itemsPerPage });
    }
  }, [currentPage]);

  var cardLoader = function cardLoader() {
    var numberOfItemsBeforeAd = 6;
    return React__default.createElement(
      reactBootstrap.Row,
      null,
      data && data.map(function (row, index) {
        var pageNumber = row.pageNumber || 1;
        return React__default.createElement(
          React__default.Fragment,
          { key: index },
          React__default.createElement(
            visibilitySensor.VisibilitySensor,
            {
              onChange: function onChange(isVisible) {
                isVisible && changePageNumber(pageNumber);
              } },
            variant === 'left' ? React__default.createElement(
              reactBootstrap.Col,
              { xl: 12, style: { marginBottom: '1rem' } },
              React__default.createElement(
                reactBootstrap.Row,
                null,
                React__default.createElement(
                  reactBootstrap.Col,
                  { xs: 3, sm: 4, md: 4, lg: 4, xl: 4, style: { padding: '0' } },
                  React__default.createElement(
                    'a',
                    { rel: 'noopener', href: row.href, target: '_blank' },
                    React__default.createElement('img', { style: { width: '100%', borderRadius: '0 0 0 10%', marginBottom: '20px', borderTop: '1px solid #EEE' }, src: row.thumbnail })
                  )
                ),
                React__default.createElement(
                  reactBootstrap.Col,
                  { xs: 9, sm: 8, md: 8, lg: 8, xl: 8, style: { paddingTop: '10px', marginBottom: '20px', borderTop: '1px solid #EEE' } },
                  React__default.createElement(
                    'a',
                    { rel: 'noopener', href: row.href, target: '_blank' },
                    React__default.createElement('h4', { className: 'mb-1', style: { fontWeight: '500', fontSize: '22px' }, dangerouslySetInnerHTML: { __html: row.title } }),
                    React__default.createElement(
                      'p',
                      { className: 'mb-2' },
                      row.date
                    ),
                    React__default.createElement('p', { dangerouslySetInnerHTML: { __html: row.intro } })
                  )
                )
              )
            ) : React__default.createElement(
              reactBootstrap.Row,
              { style: { margin: '0', padding: '0' } },
              React__default.createElement(
                reactBootstrap.Col,
                { xs: 9, sm: 8, lg: 8, xl: 8 },
                React__default.createElement(
                  'a',
                  { rel: 'noopener', href: row.href, target: '_blank' },
                  React__default.createElement('h4', { className: 'mb-1', style: { fontWeight: '500', fontSize: '22px' }, dangerouslySetInnerHTML: { __html: row.title } }),
                  React__default.createElement(
                    'p',
                    null,
                    row.date
                  ),
                  React__default.createElement('p', { dangerouslySetInnerHTML: { __html: row.intro } })
                )
              ),
              React__default.createElement(
                reactBootstrap.Col,
                { xs: 3, sm: 4, lg: 4, xl: 4 },
                React__default.createElement(
                  'a',
                  { rel: 'noopener', href: row.href, target: '_blank' },
                  React__default.createElement('img', { style: { width: '100%', borderRadius: '0 0 10% 0' }, src: row.thumbnail && urlFor(row.thumbnail.asset).url() })
                )
              )
            )
          ),
          main.main_36 && rightItems && (index + 1) % numberOfItemsBeforeAd === 0 && React__default.createElement(
            'div',
            { style: { margin: '0 auto' } },
            renderMobileAd(index, numberOfItemsBeforeAd)
          )
        );
      })
    );
  };

  var renderMobileAd = function renderMobileAd(index, numberOfItemsBeforeAd) {
    var i = ((index + 1) / numberOfItemsBeforeAd - 1) % rightItems.length;
    return React__default.createElement(
      reactBootstrap.Col,
      { md: 12, style: { display: 'flex', flex: '1 0 auto' } },
      rightItems[i].component
    );
  };

  var renderManualPagination = function renderManualPagination() {
    var currentPage = 1;
    return React__default.createElement(
      'div',
      { className: 'd-flex justify-content-between' },
       currentPage > 1 ,
      React__default.createElement(
        'a',
        { href: '?page=' + (currentPage + 1) },
        'Next >>'
      )
    );
  };

  if (isLoading) {
    return React__default.createElement(
      'div',
      { style: { display: 'flex', justifyContent: 'center', marginTop: '48px' } },
      React__default.createElement(
        reactBootstrap.Spinner,
        { animation: 'border', role: 'status' },
        React__default.createElement(
          'span',
          { className: 'sr-only' },
          'Loading...'
        )
      )
    );
  }

  if (data.length > 0) {
    return React__default.createElement(
      'div',
      { className: 'contentDeck' },
      autoScroll ? React__default.createElement(
        React__default.Fragment,
        null,
        React__default.createElement(
          'style',
          { jsx: true },
          '\n                .infinite-scroll-component {\n                  overflow: hidden !important;\n                }\n              '
        ),
        React__default.createElement(
          index_es.InfiniteScroll,
          {
            dataLength: data.length,
            next: loadMore,
            hasMore: scrolling,
            scrollThreshold: 0.9,
            loader: React__default.createElement(
              'div',
              { style: { textAlign: 'center' } },
              React__default.createElement(
                reactBootstrap.Spinner,
                { animation: 'border', role: 'status' },
                React__default.createElement(
                  'span',
                  { className: 'sr-only' },
                  'Loading...'
                )
              )
            ),
            endMessage: React__default.createElement(
              'p',
              { style: { textAlign: 'center' } },
              React__default.createElement(
                'b',
                null,
                'Yay! You have seen it all'
              )
            ) },
          React__default.createElement(
            reactBootstrap.Container,
            null,
            cardLoader()
          )
        ),
        React__default.createElement(
          'noscript',
          null,
          renderManualPagination()
        )
      ) : React__default.createElement(
        React__default.Fragment,
        null,
        React__default.createElement(
          reactBootstrap.Container,
          null,
          cardLoader()
        ),
        React__default.createElement(
          'div',
          { style: { padding: '0px 10px' } },
          scrolling ? React__default.createElement(
            'button',
            {
              style: { margin: 'auto', width: '100%' },
              onClick: function onClick(e) {
                loadMore();
              } },
            'Load More'
          ) : React__default.createElement(
            'p',
            { style: { textAlign: 'center' } },
            React__default.createElement(
              'b',
              null,
              'End of data'
            )
          )
        ),
        React__default.createElement(
          'noscript',
          null,
          renderManualPagination()
        )
      )
    );
  } else {
    return React__default.createElement(
      'div',
      null,
      React__default.createElement(
        'div',
        null,
        'No data found '
      )
    );
  }
};

module.exports = CMEDeck;
