import _regeneratorRuntime from "@babel/runtime/regenerator";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";

var _marked = /*#__PURE__*/_regeneratorRuntime.mark(fetchExportSubmissionsRequestSaga),
    _marked2 = /*#__PURE__*/_regeneratorRuntime.mark(fetchExportSubmissions),
    _marked3 = /*#__PURE__*/_regeneratorRuntime.mark(watchExport);

import { takeEvery, all, put, call, select } from 'redux-saga/effects';
import { SubmissionSearch, searchSubmissions } from '@kineticdata/react';
import { actions, types } from '../modules/export';
import isarray from 'isarray';
export function fetchExportSubmissionsRequestSaga(_ref) {
  var _ref$payload, formSlug, queryBuilder, schedulerIds, eventType, dates, _ref$payload$dateFiel, dateFieldName, kappSlug, dateParts, i;

  return _regeneratorRuntime.wrap(function fetchExportSubmissionsRequestSaga$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          _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;
          _context.next = 3;
          return select(function (state) {
            return state.app.kappSlug;
          });

        case 3:
          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 = 8;
          return 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 (isarray(query)) {
                return [].concat(_toConsumableArray(searchers), _toConsumableArray(query));
              } else {
                return [].concat(_toConsumableArray(searchers), [query]);
              }
            }, [])
          });

        case 8:
        case "end":
          return _context.stop();
      }
    }
  }, _marked);
}

var buildSearcher = function buildSearcher(_ref2) {
  var queryBuilder = _ref2.queryBuilder,
      schedulerId = _ref2.schedulerId,
      eventType = _ref2.eventType,
      dates = _ref2.dates,
      dateFieldName = _ref2.dateFieldName;
  var searcher = new 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, formSlug, searchers, results, _results$reduce, submissions, error, nextSearchers;

  return _regeneratorRuntime.wrap(function fetchExportSubmissions$(_context2) {
    while (1) {
      switch (_context2.prev = _context2.next) {
        case 0:
          kappSlug = _ref3.kappSlug, formSlug = _ref3.formSlug, searchers = _ref3.searchers;
          _context2.next = 3;
          return all(searchers.map(function (searcher) {
            return call(searchSubmissions, {
              search: searcher.build(),
              kapp: kappSlug,
              form: formSlug
            });
          }));

        case 3:
          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, _toConsumableArray(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 = 10;
            break;
          }

          _context2.next = 8;
          return put(actions.fetchExportSubmissionsFailure(error));

        case 8:
          _context2.next = 12;
          break;

        case 10:
          _context2.next = 12;
          return put(actions.fetchExportSubmissionsSuccess(submissions));

        case 12:
          if (!(nextSearchers.length > 0)) {
            _context2.next = 17;
            break;
          }

          _context2.next = 15;
          return call(fetchExportSubmissions, {
            kappSlug: kappSlug,
            formSlug: formSlug,
            searchers: nextSearchers
          });

        case 15:
          _context2.next = 19;
          break;

        case 17:
          _context2.next = 19;
          return put(actions.fetchExportSubmissionsComplete());

        case 19:
        case "end":
          return _context2.stop();
      }
    }
  }, _marked2);
}

export function watchExport() {
  return _regeneratorRuntime.wrap(function watchExport$(_context3) {
    while (1) {
      switch (_context3.prev = _context3.next) {
        case 0:
          _context3.next = 2;
          return takeEvery(types.FETCH_EXPORT_SUBMISSIONS_REQUEST, fetchExportSubmissionsRequestSaga);

        case 2:
        case "end":
          return _context3.stop();
      }
    }
  }, _marked3);
}