'use strict';

var asyncToGenerator = require('./asyncToGenerator-65df6bf8.js');
var toConsumableArray = require('./toConsumableArray-d7797c2b.js');
var React = require('react');
var ReactGA = require('react-ga');
var index = require('./index-fc2f1ca2.js');
var main = require('./main-1ec1de84.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('./events-1b438fe7.js');
require('prop-types');

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

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

var _this = undefined;

var AdSlotsProvider = function AdSlotsProvider(_ref) {
  var children = _ref.children,
      networkID = _ref.networkID,
      _ref$targeting = _ref.targeting,
      targeting = _ref$targeting === undefined ? {} : _ref$targeting,
      _ref$singleRequest = _ref.singleRequest,
      singleRequest = _ref$singleRequest === undefined ? true : _ref$singleRequest,
      _ref$autoRefresh = _ref.autoRefresh,
      autoRefresh = _ref$autoRefresh === undefined ? false : _ref$autoRefresh,
      _ref$refreshADs = _ref.refreshADs,
      refreshADs = _ref$refreshADs === undefined ? {} : _ref$refreshADs,
      _ref$refreshInterval = _ref.refreshInterval,
      refreshInterval = _ref$refreshInterval === undefined ? 60 : _ref$refreshInterval,
      _ref$disableInitialLo = _ref.disableInitialLoad,
      disableInitialLoad = _ref$disableInitialLo === undefined ? false : _ref$disableInitialLo;

  var logEvent = function logEvent(action, category, GA_TRACKING_ID) {
    if (!GA_TRACKING_ID && typeof window !== 'undefined') GA_TRACKING_ID = sessionStorage.getItem('GA_TRACKING_ID');

    if (GA_TRACKING_ID && GA_TRACKING_ID.includes(',')) {
      ReactGA__default['default'].event({
        category: category,
        action: action,
        nonInteraction: true
      }, GA_TRACKING_ID.split(',').map(function (id, index) {
        return 'ga_id_' + ++index;
      }));
    } else {
      ReactGA__default['default'].event({
        category: category,
        action: action,
        nonInteraction: true
      });
    }
  };
  React.useEffect(function () {
    // Refresh ADs after every one minute if user didn't scroll.
    // refreshInterval accepts time in seconds and default is 60 seconds
    var generateAdsToRefresh = function () {
      var _ref2 = asyncToGenerator._asyncToGenerator( /*#__PURE__*/asyncToGenerator.regenerator.mark(function _callee(ads) {
        var googletag, slots, domAds, adsToRefresh;
        return asyncToGenerator.regenerator.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return index.lib_3.getGoogletag();

              case 2:
                googletag = _context.sent;

                if (!(googletag && googletag.pubadsReady)) {
                  _context.next = 8;
                  break;
                }

                slots = googletag.pubads().getSlots();
                domAds = slots.map(function (slot) {
                  return slot.getSlotId().getDomId();
                });
                adsToRefresh = domAds.reduce(function (acc, item) {
                  ads.forEach(function (ad) {
                    if (item.includes(ad)) {
                      acc = [].concat(toConsumableArray._toConsumableArray(acc), [item]);
                    }
                  });
                  return acc;
                }, []);
                return _context.abrupt('return', adsToRefresh);

              case 8:
                return _context.abrupt('return', ads);

              case 9:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, _this);
      }));

      return function generateAdsToRefresh(_x) {
        return _ref2.apply(this, arguments);
      };
    }();
    var isScrolling = void 0;
    var adRefreshCount = 0;
    var refreshADsAfterInterval = function refreshADsAfterInterval() {
      isScrolling = setInterval(asyncToGenerator._asyncToGenerator( /*#__PURE__*/asyncToGenerator.regenerator.mark(function _callee2() {
        var _refreshADs$mobileAds, mobileAds, _refreshADs$desktopAd, desktopAds, ads;

        return asyncToGenerator.regenerator.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _refreshADs$mobileAds = refreshADs.mobileAds, mobileAds = _refreshADs$mobileAds === undefined ? ['leaderboard-ad'] : _refreshADs$mobileAds, _refreshADs$desktopAd = refreshADs.desktopAds, desktopAds = _refreshADs$desktopAd === undefined ? [] : _refreshADs$desktopAd;
                ads = [];

                if (!main.main_43) {
                  _context2.next = 8;
                  break;
                }

                _context2.next = 5;
                return generateAdsToRefresh(mobileAds);

              case 5:
                ads = _context2.sent;
                _context2.next = 12;
                break;

              case 8:
                if (!main.main_24) {
                  _context2.next = 12;
                  break;
                }

                _context2.next = 11;
                return generateAdsToRefresh(desktopAds);

              case 11:
                ads = _context2.sent;

              case 12:
                index.lib_3.refresh.apply(index.lib_3, toConsumableArray._toConsumableArray(ads));
                logEvent('AD Refresh', 'AD');
                adRefreshCount++;
                console.log('NumOfTimesAd refreshed', adRefreshCount);
                if (adRefreshCount == 5) clearInterval(isScrolling);

              case 17:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, _this);
      })), parseInt(refreshInterval) * 1000);
    };
    autoRefresh && refreshADsAfterInterval();
    autoRefresh && window.addEventListener('scroll', function () {
      clearInterval(isScrolling);
      refreshADsAfterInterval();
    }, false);
    return function () {
      clearInterval(isScrolling);
    };
  }, []);

  return React__default['default'].createElement(
    index.lib_1,
    {
      dfpNetworkId: networkID,
      targeting: targeting,
      singleRequest: singleRequest,
      lazyLoad: { fetchMarginPercent: 0, renderMarginPercent: 0, mobileScaling: 1.0 },
      disableInitialLoad: disableInitialLoad },
    children
  );
};

module.exports = AdSlotsProvider;
