'use strict';

var defineProperty = require('./defineProperty-9673846a.js');
var asyncToGenerator = require('./asyncToGenerator-77821af0.js');
var _typeof = require('./typeof-567e31ff.js');
var _extends = require('./extends-7c86182f.js');
var slicedToArray = require('./slicedToArray-067dd3bc.js');
var React = require('react');
var MediaSeriesCard = require('./MediaSeriesCard-bf5492a6.js');
require('./index-50be6759.js');
require('react-dom');
var Link = require('next/link');
var MasterDeck = require('./MasterDeck.js');
var BlockContent = require('./BlockContent-9ebd251f.js');
var getSerializers = require('./index-af49d679.js');
require('./_commonjsHelpers-06173234.js');
require('./define-property-e8404b64.js');
require('./core.get-iterator-method-5643aa10.js');
require('./web.dom.iterable-d98303e0.js');
require('./_library-dd23b178.js');
require('./_iter-detect-b1df62f0.js');
require('./_is-array-54228b29.js');
require('./_object-pie-083f2dd6.js');
require('prop-types');
require('./index-eadd5035.js');
require('./urlFor.js');
require('./index-d48b231c.js');
require('./moment-aca40de1.js');
require('./style-inject.es-dcee06b6.js');
require('./toConsumableArray-d7797c2b.js');
require('./inherits-de66ea16.js');
require('./_object-sap-d1978572.js');
require('./index-fc2f1ca2.js');
require('./events-1b438fe7.js');
require('react-bootstrap/Container');
require('react-bootstrap/Row');
require('react-bootstrap/Col');
require('react-bootstrap/Card');
require('next/router');
require('./lodash-f0783643.js');
require('./debounce-d4a2369b.js');
require('./isSymbol-03abbdf0.js');
require('./toNumber-5e1fac58.js');
require('./index.es-f3e47207.js');
require('./visibility-sensor-eb2c5b69.js');
require('./ADlgInfeed-950b414b.js');
require('./AdSlot.js');
require('./Beam.js');
require('./stringify-f7a37a8d.js');
require('./Segment.js');
require('./main-f1c77adb.js');
require('./ADInfeed-bce0ba07.js');
require('react-bootstrap');
require('./index-187c967e.js');
require('./util-93a37fd0.js');
require('./brightcove-react-player-loader.es-a195642e.js');
require('./GroupDeck.js');
require('./smoothscroll-99df7f93.js');
require('./SocialShare.js');
require('next/head');
require('react-share');
require('./_object-to-array-ce86cae7.js');
require('react-bootstrap/Pagination');
require('react-bootstrap/Button');
require('./entities-df1aed86.js');
require('./index.esm-d81454e7.js');
require('./iconBase-be4097c0.js');
require('react-bootstrap/Figure');
require('react-bootstrap/OverlayTrigger');
require('react-bootstrap/Tooltip');
require('react-bootstrap/Popover');

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

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var Link__default = /*#__PURE__*/_interopDefaultLegacy(Link);

var _this = undefined;

var Filter = function Filter(_ref) {
  var filterData = _ref.filterData,
      setFilterTopicID = _ref.setFilterTopicID;

  if (!filterData || filterData.length == 0) return null;

  var _useState = React.useState(null),
      _useState2 = slicedToArray._slicedToArray(_useState, 2),
      parentData = _useState2[0],
      setParentData = _useState2[1];

  var _useState3 = React.useState(null),
      _useState4 = slicedToArray._slicedToArray(_useState3, 2),
      childData = _useState4[0],
      setChildData = _useState4[1];

  var _useState5 = React.useState(null),
      _useState6 = slicedToArray._slicedToArray(_useState5, 2),
      grandChildData = _useState6[0],
      setGrandChildData = _useState6[1];
  /*
    {parent: showAll,
      chidlren: show selected from parent,
        grandchildren: show selected from children
    }
    */


  React.useEffect(function () {
    if (filterData.length < 2) {
      setChildData({ name: null, data: filterData[0].children, _id: filterData[0]._id });
    } else {
      setParentData({ name: null, data: filterData });
    }
  }, []);

  var handleFilterSelect = function handleFilterSelect(group, type) {
    if (type === 'parent') {
      setParentData(function (prevState) {
        return _extends._extends({}, prevState, { name: group.name ? group.name : null });
      });
      if (group && group.children && group.children.length > 0) {
        setChildData({ data: group.children, _id: group._id });
        setFilterTopicID(group._id);
      } else {
        //handle filter
        setChildData(null);
        setGrandChildData(null);
        setFilterTopicID(group._id ? group._id : 'all');
      }
    }
    if (type === 'child') {
      setChildData(function (prevState) {
        return _extends._extends({}, prevState, { name: group.name ? group.name : null, _id: group._id });
      });
      if (group && group.grandchildren && group.grandchildren.length > 0) {
        setGrandChildData({ data: group.grandchildren, _id: group._id });
        setFilterTopicID(group._id);
        var topics = [];
        topics.push(group._id);
        group.grandchildren.forEach(function (topic) {
          topics.push(topic._id);
        });
        setFilterTopicID(topics);
      } else {
        //handle filter
        setGrandChildData(null);
        setFilterTopicID(group._id ? group._id : 'all');
      }
    }
    if (type === 'grandchild') {
      setGrandChildData(function (prevState) {
        return _extends._extends({}, prevState, { name: group.name ? group.name : 'All', _id: group._id });
      });
      //handle filter
      if (!group._id) {
        var _topics = [];
        _topics.push(childData._id);
        grandChildData.data.forEach(function (topic) {
          _topics.push(topic._id);
        });
        setFilterTopicID(_topics);
      } else {
        setFilterTopicID([group._id, childData._id]);
      }
    }
  };

  return React__default['default'].createElement(
    'div',
    { className: 'flex-container' },
    parentData && React__default['default'].createElement(
      MediaSeriesCard.DropdownButton,
      { drop: 'down', style: { borderRadius: '3px' }, className: 'filter-btn', title: parentData.name ? parentData.name : 'Filter By Category' },
      React__default['default'].createElement(
        MediaSeriesCard.Dropdown.Item,
        { onSelect: function onSelect() {
            return handleFilterSelect({}, 'parent');
          } },
        'All'
      ),
      parentData.data.map(function (docGroup) {
        if (!docGroup._id) return null;
        return React__default['default'].createElement(
          MediaSeriesCard.Dropdown.Item,
          { key: docGroup._id, onSelect: function onSelect() {
              return handleFilterSelect(docGroup, 'parent');
            } },
          docGroup.name
        );
      })
    ),
    childData && childData.data && childData.data.length > 0 && React__default['default'].createElement(
      MediaSeriesCard.DropdownButton,
      { drop: 'down', style: { borderRadius: '3px' }, className: 'filter-btn ml-3', title: childData.name ? childData.name : 'Filter By Topic' },
      React__default['default'].createElement(
        MediaSeriesCard.Dropdown.Item,
        { onSelect: function onSelect() {
            return handleFilterSelect({}, 'child');
          } },
        'All'
      ),
      childData.data.map(function (docGroup) {
        if (!docGroup._id) return null;
        return React__default['default'].createElement(
          MediaSeriesCard.Dropdown.Item,
          { key: docGroup._id, onSelect: function onSelect() {
              return handleFilterSelect(docGroup, 'child');
            } },
          docGroup.name
        );
      })
    ),
    grandChildData && grandChildData.data && grandChildData.data.length > 0 && React__default['default'].createElement(
      MediaSeriesCard.DropdownButton,
      { drop: 'down', style: { borderRadius: '3px' }, className: 'filter-btn ml-3', title: grandChildData.name ? grandChildData.name : 'Select Sub Topic' },
      React__default['default'].createElement(
        MediaSeriesCard.Dropdown.Item,
        { onSelect: function onSelect() {
            return handleFilterSelect({}, 'grandchild');
          } },
        'All'
      ),
      grandChildData.data.map(function (docGroup) {
        if (!docGroup._id) return null;
        return React__default['default'].createElement(
          MediaSeriesCard.Dropdown.Item,
          { key: docGroup._id, onSelect: function onSelect() {
              return handleFilterSelect(docGroup, 'grandchild');
            } },
          docGroup.name
        );
      })
    ),
    React__default['default'].createElement(
      'style',
      { jsx: 'true' },
      '\n        .flex-container {\n          display: flex;\n          flex-direction: row;\n          align-items: center;\n        }\n        .filter-btn button {\n          border-radius: 3px;\n          z-index: 99999;\n        }\n        .filter-btn .dropdown-menu {\n          z-index: 9999999;\n        }\n        @media (max-width: 768px) {\n          .flex-container {\n            flex-direction: column;\n            align-items: flex-start;\n          }\n        }\n      '
    )
  );
};

var MediaSeriesLanding = function MediaSeriesLanding(props) {
  var client = props.client,
      pageview = props.pageview,
      currentPage = props.currentPage,
      docGroupID = props.docGroupID,
      parentUrl = props.parentUrl;

  var _useState7 = React.useState(false),
      _useState8 = slicedToArray._slicedToArray(_useState7, 2),
      filterTopicID = _useState8[0],
      setFilterTopicID = _useState8[1];

  var _useState9 = React.useState(props.seriesData),
      _useState10 = slicedToArray._slicedToArray(_useState9, 2),
      seriesData = _useState10[0],
      setSeriesData = _useState10[1];

  var _useState11 = React.useState(props.params),
      _useState12 = slicedToArray._slicedToArray(_useState11, 2),
      params = _useState12[0],
      setParams = _useState12[1];

  var _useState13 = React.useState(props.query),
      _useState14 = slicedToArray._slicedToArray(_useState13, 2),
      query = _useState14[0],
      setQuery = _useState14[1];

  React.useEffect(function () {
    if (filterTopicID) {
      fetchFilteredData();
    }
  }, [filterTopicID]);

  var fetchFilteredData = function () {
    var _ref2 = asyncToGenerator._asyncToGenerator( /*#__PURE__*/asyncToGenerator.regenerator.mark(function _callee() {
      var newParams, filterQuery, x, seriesQuery, newData;
      return asyncToGenerator.regenerator.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              newParams = _extends._extends({}, params, { from: 0, to: 10 });
              filterQuery = void 0;

              if ((typeof filterTopicID === 'undefined' ? 'undefined' : _typeof._typeof(filterTopicID)) == 'object') {
                filterQuery = '&& (';
                for (x = 0; x < filterTopicID.length; x++) {
                  filterQuery = filterQuery + (' references(\'' + filterTopicID[x] + '\') ');
                  if (x == filterTopicID.length - 1) {
                    filterQuery = filterQuery + ' )';
                  } else {
                    filterQuery = filterQuery + ' || ';
                  }
                }
              } else {
                filterQuery = filterTopicID !== 'all' ? ' && references(\'' + filterTopicID + '\')' : '';
              }

              seriesQuery = '*[_type == \'documentGroup\' && references(\'' + docGroupID + '\') ' + filterQuery + ' && isSeries != false && isShow != false && defined(published) && dateTime(published) <= dateTime(now())] | order(published desc) [$from...$to] {\n      _id,\n      name,\n      identifier,\n      published,\n      thumbnail,\n      description,\n      topicMapping[]->,\n      \'pageNumber\': ' + currentPage + ',\n      \'parentUrl\': \'' + parentUrl + '\'\n  }';
              _context.next = 6;
              return client.fetch(seriesQuery, newParams);

            case 6:
              newData = _context.sent;

              setParams(newParams);
              setQuery(seriesQuery);
              setSeriesData(newData);

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

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

  if (props.statusCode === 404) {
    return React__default['default'].createElement(
      'div',
      { className: 'd-flex flex-column align-items-center mt-3' },
      React__default['default'].createElement(
        'h3',
        null,
        '404: Resource not found'
      ),
      React__default['default'].createElement(
        'p',
        null,
        'We seem to have misplaced the page you\'re looking for. Sorry! Please try checking the URL for errors.'
      ),
      React__default['default'].createElement(
        'p',
        null,
        'Click here to',
        React__default['default'].createElement(
          Link__default['default'],
          { href: '/' },
          React__default['default'].createElement(
            'a',
            { style: { color: 'blue', textDecoration: 'underline' } },
            ' return to homepage.'
          )
        )
      )
    );
  }

  return React__default['default'].createElement(
    'div',
    { className: 'mb-5' },
    props.docGroup && props.docGroup.description && React__default['default'].createElement(BlockContent.BlockContent, { blocks: props.docGroup.description, serializers: getSerializers.getSerializers(client) }),
    props.taxonomyFilter && props.taxonomyFilter && React__default['default'].createElement(
      'div',
      { className: '' },
      React__default['default'].createElement(Filter, { setFilterTopicID: setFilterTopicID, filterData: props.taxonomyFilter }),
      React__default['default'].createElement('hr', null)
    ),
    seriesData && React__default['default'].createElement(MasterDeck, {
      deck: MediaSeriesCard.MediaSeriesCard,
      variant: 'left',
      defaultImage: '/placeholder.jpg',
      client: client,
      dataRecord: seriesData,
      query: query && query,
      params: params && params,
      currentPage: currentPage,
      pageview: pageview,
      autoScroll: true,
      seoPaginate: true
    })
  );
};

MediaSeriesLanding.getInitialData = function () {
  var _ref3 = asyncToGenerator._asyncToGenerator( /*#__PURE__*/asyncToGenerator.regenerator.mark(function _callee2(ctx, client, cache) {
    var _ref4;

    var urlQuery, pathname, identifier, itemsPerPage, currentPage, start, statusCode, params, docGroupID, seriesQuery, seriesData, allSeries, buildUsedTopicsArray, usedTopics, taxonomyFilter;
    return asyncToGenerator.regenerator.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            urlQuery = ctx.query, pathname = ctx.pathname;
            identifier = pathname.replace('/', '');
            itemsPerPage = 10;
            currentPage = urlQuery.page ? parseInt(urlQuery.page) : 1;
            start = (currentPage - 1) * itemsPerPage;
            statusCode = 200;
            params = {
              count: itemsPerPage,
              from: start,
              to: start + itemsPerPage,
              url: pathname
            };
            _context2.next = 9;
            return client.fetch('*[_type == \'documentGroup\' && identifier.current == \'' + identifier + '\'][0]{\n    _id, \n    isGated,\n    name,\n    description\n  }');

          case 9:
            docGroupID = _context2.sent;
            seriesQuery = '*[_type == \'documentGroup\' && references(\'' + docGroupID._id + '\') && isSeries != false && isShow != false && defined(published) && dateTime(published) <= dateTime(now()) ] | order(published desc) [$from...$to] {\n        _id,\n        name,\n        identifier,\n        published,\n        thumbnail{ ..., asset-> },\n        description,\n        topicMapping[]->,\n        isGated,\n        \'pageNumber\': ' + currentPage + ',\n        \'parentUrl\': \'' + identifier + '\'\n    }';
            _context2.next = 13;
            return client.fetch(seriesQuery, params);

          case 13:
            seriesData = _context2.sent;
            _context2.next = 16;
            return client.fetch('*[_type == \'documentGroup\' && references(\'' + docGroupID._id + '\') && isSeries != false && isShow != false && defined(published) && dateTime(published) <= dateTime(now()) ]  {\n    topicMapping[]->\n  }');

          case 16:
            allSeries = _context2.sent;

            //Take all series topicMapping and put in an array
            buildUsedTopicsArray = function buildUsedTopicsArray(seriesArray) {
              var usedTopics = [];
              for (var x = 0; x < seriesArray.length; x++) {
                if (seriesArray[x].topicMapping) {
                  seriesArray[x].topicMapping.forEach(function (topic) {
                    if (!usedTopics.includes(topic._id)) {
                      usedTopics.push(topic._id);
                    }
                  });
                }
              }
              return usedTopics;
            };

            usedTopics = buildUsedTopicsArray(allSeries);
            _context2.next = 21;
            return client.fetch('\n  *[_type == \'taxonomy\' && !defined(parent) && isMainTopic]{\n    _id,\n    identifier,\n    name,\n    "children": *[_type == \'taxonomy\' && references(^._id)]{\n        _id,\n        name,\n        identifier,\n        "grandchildren": *[_type == \'taxonomy\' && references(^._id)]\n      }\t\n    }');

          case 21:
            taxonomyFilter = _context2.sent;


            taxonomyFilter.forEach(function (topic) {
              if (topic.children) {
                topic.children.forEach(function (child) {
                  if (child.grandchildren) {
                    child.grandchildren = child.grandchildren.filter(function (grandchild) {
                      if (!usedTopics.includes(grandchild._id)) {
                        return false;
                      }
                      return true;
                    });
                  }
                  if (!usedTopics.includes(child._id) || !child.grandchildren) {
                    child._id = null;
                    child.name = null;
                  }
                });

                topic.children = topic.children.filter(function (child) {
                  return child._id !== null;
                });
              }
            });

            if (currentPage > 1 && seriesData.length === 0) {
              statusCode = 404;
            }

            return _context2.abrupt('return', (_ref4 = { seriesData: seriesData, query: seriesQuery, params: params, currentPage: currentPage, taxonomyFilter: taxonomyFilter, identifier: identifier, docGroupID: docGroupID._id, parentUrl: identifier, statusCode: statusCode }, defineProperty._defineProperty(_ref4, 'taxonomyFilter', taxonomyFilter), defineProperty._defineProperty(_ref4, 'docGroup', docGroupID), _ref4));

          case 25:
          case 'end':
            return _context2.stop();
        }
      }
    }, _callee2, _this);
  }));

  return function (_x, _x2, _x3) {
    return _ref3.apply(this, arguments);
  };
}();

module.exports = MediaSeriesLanding;
