"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];
var _regeneratorRuntime3 = require("@babel/runtime/helpers/regeneratorRuntime")["default"];
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.fetchExportSubmissionsRequestSaga = fetchExportSubmissionsRequestSaga;
exports.watchExport = watchExport;
var _regeneratorRuntime2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/regeneratorRuntime"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/toConsumableArray"));
var _effects = require("redux-saga/effects");
var _react = require("@kineticdata/react");
var _export = require("../modules/export");
var _isarray = _interopRequireDefault(require("isarray"));
var _marked = /*#__PURE__*/_regeneratorRuntime3().mark(watchExport);
function fetchExportSubmissionsRequestSaga(_ref) {
  var _ref$payload = _ref.payload,
    formSlug = _ref$payload.formSlug,
    queryBuilder = _ref$payload.queryBuilder,
    schedulerIds = _ref$payload.schedulerIds,
    eventType = _ref$payload.eventType,
    dates = _ref$payload.dates,
    _ref$payload$dateFiel = _ref$payload.dateFieldName,
    dateFieldName = _ref$payload$dateFiel === void 0 ? 'Event Date' : _ref$payload$dateFiel;
  return /*#__PURE__*/(0, _regeneratorRuntime2["default"])().mark(function _callee() {
    var kappSlug, dateParts, i;
    return (0, _regeneratorRuntime2["default"])().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return (0, _effects.select)(function (state) {
            return state.app.kappSlug;
          });
        case 2:
          kappSlug = _context.sent;
          dateParts = [];
          if (dates && dates.length > 8) {
            for (i = 0; i <= dates.length; i += 8) {
              dateParts.push(dates.slice(i, i + 8));
            }
          }
          _context.next = 7;
          return (0, _effects.call)(fetchExportSubmissions, {
            kappSlug: kappSlug,
            formSlug: formSlug,
            searchers: schedulerIds.map(function (schedulerId) {
              if (dateParts.length > 0) {
                return dateParts.map(function (datePart) {
                  return buildSearcher({
                    queryBuilder: queryBuilder,
                    schedulerId: schedulerId,
                    eventType: eventType,
                    dates: datePart,
                    dateFieldName: dateFieldName
                  });
                });
              } else {
                return buildSearcher({
                  queryBuilder: queryBuilder,
                  schedulerId: schedulerId,
                  eventType: eventType,
                  dates: dates,
                  dateFieldName: dateFieldName
                });
              }
            }).reduce(function (searchers, query) {
              if ((0, _isarray["default"])(query)) {
                return [].concat((0, _toConsumableArray2["default"])(searchers), (0, _toConsumableArray2["default"])(query));
              } else {
                return [].concat((0, _toConsumableArray2["default"])(searchers), [query]);
              }
            }, [])
          });
        case 7:
        case "end":
          return _context.stop();
      }
    }, _callee);
  })();
}
var buildSearcher = function buildSearcher(_ref2) {
  var queryBuilder = _ref2.queryBuilder,
    schedulerId = _ref2.schedulerId,
    eventType = _ref2.eventType,
    dates = _ref2.dates,
    dateFieldName = _ref2.dateFieldName;
  var searcher = new _react.SubmissionSearch();
  searcher.include('details,values,form.fields');
  searcher.limit(1000);
  if (typeof queryBuilder === 'function') {
    queryBuilder(searcher);
  }
  if (dates && dates.length > 1) {
    searcher.or();
    dates.forEach(function (date) {
      searcher.and();
      searcher.eq('values[Scheduler Id]', schedulerId);
      if (eventType) {
        searcher.eq('values[Event Type]', eventType);
      }
      searcher.eq("values[".concat(dateFieldName, "]"), date);
      searcher.end();
    });
    searcher.end();
  } else {
    searcher.eq('values[Scheduler Id]', schedulerId);
    if (eventType) {
      searcher.eq('values[Event Type]', eventType);
    }
    if (dates && dates.length === 1) {
      searcher.eq("values[".concat(dateFieldName, "]"), dates[0]);
    }
  }
  return searcher;
};
function fetchExportSubmissions(_ref3) {
  var kappSlug = _ref3.kappSlug,
    formSlug = _ref3.formSlug,
    searchers = _ref3.searchers;
  return /*#__PURE__*/(0, _regeneratorRuntime2["default"])().mark(function _callee2() {
    var results, _results$reduce, submissions, error, nextSearchers;
    return (0, _regeneratorRuntime2["default"])().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 2;
          return (0, _effects.all)(searchers.map(function (searcher) {
            return (0, _effects.call)(_react.searchSubmissions, {
              search: searcher.build(),
              kapp: kappSlug,
              form: formSlug
            });
          }));
        case 2:
          results = _context2.sent;
          _results$reduce = results.reduce(function (data, _ref4, index) {
            var submissions = _ref4.submissions,
              _ref4$nextPageToken = _ref4.nextPageToken,
              nextPageToken = _ref4$nextPageToken === void 0 ? null : _ref4$nextPageToken,
              error = _ref4.error;
            if (!data.error) {
              if (error) {
                data.error = error;
              } else {
                var _data$submissions;
                (_data$submissions = data.submissions).push.apply(_data$submissions, (0, _toConsumableArray2["default"])(submissions));
                if (nextPageToken) {
                  var searcher = searchers[index];
                  searcher.pageToken(nextPageToken);
                  data.nextSearchers.push(searcher);
                }
              }
            }
            return data;
          }, {
            submissions: [],
            error: null,
            nextSearchers: []
          }), submissions = _results$reduce.submissions, error = _results$reduce.error, nextSearchers = _results$reduce.nextSearchers;
          if (!error) {
            _context2.next = 9;
            break;
          }
          _context2.next = 7;
          return (0, _effects.put)(_export.actions.fetchExportSubmissionsFailure(error));
        case 7:
          _context2.next = 11;
          break;
        case 9:
          _context2.next = 11;
          return (0, _effects.put)(_export.actions.fetchExportSubmissionsSuccess(submissions));
        case 11:
          if (!(nextSearchers.length > 0)) {
            _context2.next = 16;
            break;
          }
          _context2.next = 14;
          return (0, _effects.call)(fetchExportSubmissions, {
            kappSlug: kappSlug,
            formSlug: formSlug,
            searchers: nextSearchers
          });
        case 14:
          _context2.next = 18;
          break;
        case 16:
          _context2.next = 18;
          return (0, _effects.put)(_export.actions.fetchExportSubmissionsComplete());
        case 18:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  })();
}
function watchExport() {
  return (0, _regeneratorRuntime2["default"])().wrap(function watchExport$(_context3) {
    while (1) switch (_context3.prev = _context3.next) {
      case 0:
        _context3.next = 2;
        return (0, _effects.takeEvery)(_export.types.FETCH_EXPORT_SUBMISSIONS_REQUEST, fetchExportSubmissionsRequestSaga);
      case 2:
      case "end":
        return _context3.stop();
    }
  }, _marked);
}