import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";

var _marked = /*#__PURE__*/_regeneratorRuntime.mark(fetchAppDataRequestSaga),
    _marked2 = /*#__PURE__*/_regeneratorRuntime.mark(fetchDisplayTeamRequestSaga),
    _marked3 = /*#__PURE__*/_regeneratorRuntime.mark(createDisplayTeamMembershipRequestSaga),
    _marked4 = /*#__PURE__*/_regeneratorRuntime.mark(deleteDisplayTeamMembershipRequestSaga),
    _marked5 = /*#__PURE__*/_regeneratorRuntime.mark(createDisplayTeamUserRequestSaga),
    _marked6 = /*#__PURE__*/_regeneratorRuntime.mark(watchTechBarApp);

import { takeEvery, put, all, call, select } from 'redux-saga/effects';
import { SubmissionSearch, searchSubmissions, fetchTeam, createUser, fetchForms, createMembership, deleteMembership } from '@kineticdata/react';
import { actions, types, Settings } from '../modules/techBarApp';
import { SCHEDULER_FORM_SLUG, TECH_BAR_SETTINGS_FORM_SLUG } from '../../constants';
import { addToast, addToastAlert } from '@kineticdata/bundle-common';
import md5 from 'md5';
export function fetchAppDataRequestSaga() {
  var schedulersQuery, settingsQuery, kappSlug, _yield$all, _yield$all2, _yield$all2$, schedulers, schedulersError, _yield$all2$2, techBarSettings, settingsError, _yield$all2$3, forms, formsError;

  return _regeneratorRuntime.wrap(function fetchAppDataRequestSaga$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          schedulersQuery = new SubmissionSearch(true);
          schedulersQuery.include('details,values');
          schedulersQuery.limit('1000');
          schedulersQuery.index('values[Type],values[Name]');
          schedulersQuery.eq('values[Type]', 'TechBar');
          settingsQuery = new SubmissionSearch(true);
          settingsQuery.include('details,values');
          settingsQuery.limit('1000');
          settingsQuery.index('values[Scheduler Id]:UNIQUE');
          _context.next = 11;
          return select(function (state) {
            return state.app.kappSlug;
          });

        case 11:
          kappSlug = _context.sent;
          _context.next = 14;
          return all([call(searchSubmissions, {
            search: schedulersQuery.build(),
            datastore: true,
            form: SCHEDULER_FORM_SLUG
          }), call(searchSubmissions, {
            search: settingsQuery.build(),
            datastore: true,
            form: TECH_BAR_SETTINGS_FORM_SLUG
          }), call(fetchForms, {
            kappSlug: kappSlug,
            include: 'details,attributes'
          })]);

        case 14:
          _yield$all = _context.sent;
          _yield$all2 = _slicedToArray(_yield$all, 3);
          _yield$all2$ = _yield$all2[0];
          schedulers = _yield$all2$.submissions;
          schedulersError = _yield$all2$.error;
          _yield$all2$2 = _yield$all2[1];
          techBarSettings = _yield$all2$2.submissions;
          settingsError = _yield$all2$2.error;
          _yield$all2$3 = _yield$all2[2];
          forms = _yield$all2$3.forms;
          formsError = _yield$all2$3.error;

          if (!(schedulersError || settingsError || formsError)) {
            _context.next = 31;
            break;
          }

          _context.next = 28;
          return put(actions.fetchAppDataFailure(schedulersError || settingsError || formsError));

        case 28:
          addToastAlert({
            title: 'Failed to load Tech Bar App.',
            message: (schedulersError || settingsError || formsError).message
          });
          _context.next = 33;
          break;

        case 31:
          _context.next = 33;
          return put(actions.fetchAppDataSuccess({
            schedulers: schedulers.map(function (scheduler) {
              return _objectSpread(_objectSpread({}, scheduler), {}, {
                settings: Settings(techBarSettings.find(function (s) {
                  return s.values['Scheduler Id'] === scheduler.values['Id'];
                }))
              });
            }),
            forms: forms
          }));

        case 33:
        case "end":
          return _context.stop();
      }
    }
  }, _marked);
}
export function fetchDisplayTeamRequestSaga(_ref) {
  var techBarName, _yield$call, team, error;

  return _regeneratorRuntime.wrap(function fetchDisplayTeamRequestSaga$(_context2) {
    while (1) {
      switch (_context2.prev = _context2.next) {
        case 0:
          techBarName = _ref.payload.techBarName;
          _context2.next = 3;
          return call(fetchTeam, {
            teamSlug: md5("Role::Tech Bar Display::".concat(techBarName)),
            include: 'attributes,memberships.user,memberships.user.attributes,memberships.user.profileAttributes'
          });

        case 3:
          _yield$call = _context2.sent;
          team = _yield$call.team;
          error = _yield$call.error;

          if (!error) {
            _context2.next = 11;
            break;
          }

          _context2.next = 9;
          return put(actions.fetchDisplayTeamFailure(error));

        case 9:
          _context2.next = 13;
          break;

        case 11:
          _context2.next = 13;
          return put(actions.fetchDisplayTeamSuccess(team));

        case 13:
        case "end":
          return _context2.stop();
      }
    }
  }, _marked2);
}
export function createDisplayTeamMembershipRequestSaga(_ref2) {
  var _ref2$payload, username, _ref2$payload$usernam, usernames, techBarName, toAdd, results, success, errorList;

  return _regeneratorRuntime.wrap(function createDisplayTeamMembershipRequestSaga$(_context3) {
    while (1) {
      switch (_context3.prev = _context3.next) {
        case 0:
          _ref2$payload = _ref2.payload, username = _ref2$payload.username, _ref2$payload$usernam = _ref2$payload.usernames, usernames = _ref2$payload$usernam === void 0 ? [] : _ref2$payload$usernam, techBarName = _ref2$payload.techBarName;
          toAdd = username ? [username] : usernames;

          if (!(toAdd.length === 0)) {
            _context3.next = 5;
            break;
          }

          addToast({
            message: 'No users selected to add.',
            severity: 'danger'
          });
          return _context3.abrupt("return");

        case 5:
          _context3.next = 7;
          return all(toAdd.map(function (u) {
            return call(createMembership, {
              team: {
                name: "Role::Tech Bar Display::".concat(techBarName)
              },
              user: {
                username: u
              }
            });
          }));

        case 7:
          results = _context3.sent;
          success = false;
          errorList = results.reduce(function (errorList, _ref3) {
            var error = _ref3.error;

            if (error) {
              return [].concat(_toConsumableArray(errorList), [error]);
            } else {
              success = true;
              return errorList;
            }
          }, []);

          if (errorList.length > 0) {
            addToastAlert({
              title: 'Error adding new users.',
              message: errorList.map(function (e) {
                return e.message;
              }).join('\n')
            });
          }

          if (!success) {
            _context3.next = 15;
            break;
          }

          addToast("User".concat(toAdd.length > 1 ? 's' : '', " added successfully."));
          _context3.next = 15;
          return put(actions.fetchDisplayTeamRequest({
            techBarName: techBarName
          }));

        case 15:
        case "end":
          return _context3.stop();
      }
    }
  }, _marked3);
}
export function deleteDisplayTeamMembershipRequestSaga(_ref4) {
  var _ref4$payload, username, techBarName, _yield$call2, error;

  return _regeneratorRuntime.wrap(function deleteDisplayTeamMembershipRequestSaga$(_context4) {
    while (1) {
      switch (_context4.prev = _context4.next) {
        case 0:
          _ref4$payload = _ref4.payload, username = _ref4$payload.username, techBarName = _ref4$payload.techBarName;
          _context4.next = 3;
          return call(deleteMembership, {
            teamSlug: md5("Role::Tech Bar Display::".concat(techBarName)),
            username: username
          });

        case 3:
          _yield$call2 = _context4.sent;
          error = _yield$call2.error;

          if (!error) {
            _context4.next = 9;
            break;
          }

          addToastAlert({
            title: 'Error removing user.',
            message: error.message
          });
          _context4.next = 12;
          break;

        case 9:
          addToast("User was removed successfully.");
          _context4.next = 12;
          return put(actions.fetchDisplayTeamRequest({
            techBarName: techBarName
          }));

        case 12:
        case "end":
          return _context4.stop();
      }
    }
  }, _marked4);
}
export function createDisplayTeamUserRequestSaga(_ref5) {
  var _ref5$payload, user, teamName, techBarName, _yield$call3, error;

  return _regeneratorRuntime.wrap(function createDisplayTeamUserRequestSaga$(_context5) {
    while (1) {
      switch (_context5.prev = _context5.next) {
        case 0:
          _ref5$payload = _ref5.payload, user = _ref5$payload.user, teamName = _ref5$payload.teamName, techBarName = _ref5$payload.techBarName;
          _context5.next = 3;
          return call(createUser, {
            user: {
              username: user.email,
              email: user.email,
              displayName: "".concat(user.firstName, " ").concat(user.lastName),
              enabled: true,
              spaceAdmin: false,
              memberships: [{
                team: {
                  name: "Role::Tech Bar Display::".concat(techBarName)
                }
              }],
              profileAttributesMap: {
                'First Name': [user.firstName],
                'Last Name': [user.lastName]
              }
            }
          });

        case 3:
          _yield$call3 = _context5.sent;
          error = _yield$call3.error;

          if (!error) {
            _context5.next = 9;
            break;
          }

          addToastAlert({
            title: 'Error creating user.',
            message: error.message
          });
          _context5.next = 12;
          break;

        case 9:
          addToast("User was created successfully.");
          _context5.next = 12;
          return put(actions.fetchDisplayTeamRequest({
            techBarName: techBarName
          }));

        case 12:
        case "end":
          return _context5.stop();
      }
    }
  }, _marked5);
}
export function watchTechBarApp() {
  return _regeneratorRuntime.wrap(function watchTechBarApp$(_context6) {
    while (1) {
      switch (_context6.prev = _context6.next) {
        case 0:
          _context6.next = 2;
          return takeEvery(types.FETCH_APP_DATA_REQUEST, fetchAppDataRequestSaga);

        case 2:
          _context6.next = 4;
          return takeEvery(types.FETCH_DISPLAY_TEAM_REQUEST, fetchDisplayTeamRequestSaga);

        case 4:
          _context6.next = 6;
          return takeEvery(types.CREATE_DISPLAY_TEAM_MEMBERSHIP_REQUEST, createDisplayTeamMembershipRequestSaga);

        case 6:
          _context6.next = 8;
          return takeEvery(types.DELETE_DISPLAY_TEAM_MEMBERSHIP_REQUEST, deleteDisplayTeamMembershipRequestSaga);

        case 8:
          _context6.next = 10;
          return takeEvery(types.CREATE_DISPLAY_TEAM_USER_REQUEST, createDisplayTeamUserRequestSaga);

        case 10:
        case "end":
          return _context6.stop();
      }
    }
  }, _marked6);
}