'use strict';

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-acb4581d.js');
require('./index-50be6759.js');
require('react-dom');
var Link = require('next/link');
var BlockContent = require('./BlockContent-9ebd251f.js');
var MasterDeckPaginated = require('./MasterDeckPaginated.js');
var getSerializers = require('./index-62c26edb.js');
require('./_commonjsHelpers-06173234.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('./stringify-f7a37a8d.js');
require('./toConsumableArray-d7797c2b.js');
require('./inherits-de66ea16.js');
require('./_object-sap-d1978572.js');
require('./define-property-e8404b64.js');
require('./index-fc2f1ca2.js');
require('./events-1b438fe7.js');
require('react-bootstrap/Container');
require('react-bootstrap/Spinner');
require('next/router');
require('./lodash-f0783643.js');
require('./main-f1c77adb.js');
require('./ADlgInfeed-24d739f6.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('./ADInfeed-44d43b8a.js');
require('./Pagination-885dcfbd.js');
require('react-paginate');
require('react-bootstrap/Button');
require('./index.esm-d51c9ac6.js');
require('./iconBase-be4097c0.js');
require('react-bootstrap');
require('./index-187c967e.js');
require('./util-93a37fd0.js');
require('./urlForFile-29d3815a.js');
require('./brightcove-react-player-loader.es-a195642e.js');
require('react-bootstrap/Modal');
require('react-bootstrap/Form');
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('./entities-df1aed86.js');
require('react-bootstrap/Row');
require('react-bootstrap/Col');
require('./index.esm-d81454e7.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;

  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.totalSeriesCount),
      _useState12 = slicedToArray._slicedToArray(_useState11, 2),
      totalSeriesCount = _useState12[0],
      setTotalSeriesCount = _useState12[1];

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

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

  var _useState17 = React.useState(props.currentPage),
      _useState18 = slicedToArray._slicedToArray(_useState17, 2),
      currentPage = _useState18[0],
      setCurrentPage = _useState18[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, seriesQuerySorts, seriesQueryProjection, seriesQueryFilters, seriesQuery, totalSeriesCountQuery, _ref3, _ref4, newData, newDataCount;

      return asyncToGenerator.regenerator.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              newParams = _extends._extends({}, params, { from: 0, to: 30 });
              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 + '\')]' : '';
              }

              seriesQuerySorts = props.seriesQuerySorts, seriesQueryProjection = props.seriesQueryProjection;
              seriesQueryFilters = props.seriesQueryFilters;

              seriesQueryFilters = filterQuery ? [seriesQueryFilters, filterQuery] : seriesQueryFilters;
              seriesQuery = ['*'].concat(seriesQueryFilters).concat(seriesQuerySorts).concat(seriesQueryProjection).join('|');
              totalSeriesCountQuery = 'count(' + ['*'].concat(seriesQueryFilters).join('|') + ')';
              _context.next = 10;
              return asyncToGenerator._Promise.all([client.fetch(seriesQuery, newParams), client.fetch(totalSeriesCountQuery)]);

            case 10:
              _ref3 = _context.sent;
              _ref4 = slicedToArray._slicedToArray(_ref3, 2);
              newData = _ref4[0];
              newDataCount = _ref4[1];


              setParams(newParams);
              setQuery(seriesQuery);
              setSeriesData(newData);
              setTotalSeriesCount(newDataCount);
              setCurrentPage(1);

            case 19:
            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: 'filter-btn-container' },
      React__default['default'].createElement(Filter, { setFilterTopicID: setFilterTopicID, filterData: props.taxonomyFilter }),
      React__default['default'].createElement('hr', null)
    ),
    seriesData && React__default['default'].createElement(MasterDeckPaginated, {
      deck: MediaSeriesCard.MediaSeriesCard,
      variant: 'left',
      defaultImage: '/placeholder.jpg',
      client: client,
      dataRecord: seriesData,
      totalDataCount: totalSeriesCount,
      query: query && query,
      params: params && params,
      currentPage: currentPage,
      pageview: pageview,
      needLargePaginateButtons: props.needLargePaginateButtons,
      seoPaginate: true
    })
  );
};

MediaSeriesLanding.getInitialData = function () {
  var _ref5 = asyncToGenerator._asyncToGenerator( /*#__PURE__*/asyncToGenerator.regenerator.mark(function _callee2(ctx, client, cache, parameters) {
    var urlQuery, pathname, identifier, itemsPerPage, currentPage, start, statusCode, params, docGroupID, seriesQueryFilters, seriesQuerySorts, seriesQueryProjection, seriesQuery, totalSeriesCountQuery, _ref6, _ref7, seriesData, totalSeriesCount, 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 = parameters && parameters.itemsPerPage ? parameters.itemsPerPage : 30;
            currentPage = urlQuery.page ? parseInt(urlQuery.page) : 1;
            start = (currentPage - 1) * itemsPerPage;
            statusCode = 200;
            params = {
              count: itemsPerPage,
              from: start,
              to: start + itemsPerPage,
              url: pathname,
              itemsPerPage: itemsPerPage
            };
            _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;
            seriesQueryFilters = '[\n    _type == \'documentGroup\' \n    && references(\'' + docGroupID._id + '\') \n    && isSeries != false \n    && isShow != false \n    && defined(published) \n    && published <= now()\n  ]';
            seriesQuerySorts = 'order(published desc) [$from...$to]';
            seriesQueryProjection = '{\n    _id,\n    name,\n    identifier,\n    published,\n    thumbnail{ ..., asset-> },\n    description,\n    topicMapping[]->,\n    isGated,\n    \'parentUrl\': \'' + identifier + '\'\n  }';
            seriesQuery = ['*'].concat(seriesQueryFilters).concat(seriesQuerySorts).concat(seriesQueryProjection).join('|');
            totalSeriesCountQuery = 'count(' + ['*'].concat(seriesQueryFilters).join('|') + ')';
            _context2.next = 17;
            return asyncToGenerator._Promise.all([client.fetch(seriesQuery, params), client.fetch(totalSeriesCountQuery)]);

          case 17:
            _ref6 = _context2.sent;
            _ref7 = slicedToArray._slicedToArray(_ref6, 2);
            seriesData = _ref7[0];
            totalSeriesCount = _ref7[1];
            _context2.next = 23;
            return client.fetch('*[_type == \'documentGroup\' && references(\'' + docGroupID._id + '\') && isSeries != false && isShow != false && defined(published) && dateTime(published) <= dateTime(now()) ]  {\n    topicMapping[]->\n  }');

          case 23:
            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.length > 0) {
                  seriesArray[x].topicMapping.forEach(function (topic) {
                    if (topic && topic._id) {
                      if (!usedTopics.includes(topic._id)) {
                        usedTopics.push(topic._id);
                      }
                    }
                  });
                }
              }
              return usedTopics;
            };

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

          case 28:
            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', {
              seriesData: seriesData,
              totalSeriesCount: totalSeriesCount,
              query: seriesQuery,
              seriesQueryFilters: seriesQueryFilters,
              seriesQuerySorts: seriesQuerySorts,
              seriesQueryProjection: seriesQueryProjection,
              params: params,
              currentPage: currentPage,
              taxonomyFilter: taxonomyFilter,
              identifier: identifier,
              docGroupID: docGroupID._id,
              parentUrl: identifier,
              statusCode: statusCode,
              docGroup: docGroupID
            });

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

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

module.exports = MediaSeriesLanding;
