"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.createDisplayTeamMembershipRequestSaga = createDisplayTeamMembershipRequestSaga;
exports.createDisplayTeamUserRequestSaga = createDisplayTeamUserRequestSaga;
exports.deleteDisplayTeamMembershipRequestSaga = deleteDisplayTeamMembershipRequestSaga;
exports.fetchAppDataRequestSaga = fetchAppDataRequestSaga;
exports.fetchDisplayTeamRequestSaga = fetchDisplayTeamRequestSaga;
exports.watchTechBarApp = watchTechBarApp;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/toConsumableArray"));
var _regeneratorRuntime2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/regeneratorRuntime"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/objectSpread2"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/slicedToArray"));
var _effects = require("redux-saga/effects");
var _react = require("@kineticdata/react");
var _techBarApp = require("../modules/techBarApp");
var _constants = require("../../constants");
var _bundleCommon = require("@kineticdata/bundle-common");
var _md = _interopRequireDefault(require("md5"));
var _marked = /*#__PURE__*/_regeneratorRuntime3().mark(fetchAppDataRequestSaga),
  _marked2 = /*#__PURE__*/_regeneratorRuntime3().mark(watchTechBarApp);
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 (0, _regeneratorRuntime2["default"])().wrap(function fetchAppDataRequestSaga$(_context) {
    while (1) switch (_context.prev = _context.next) {
      case 0:
        schedulersQuery = new _react.SubmissionSearch(true);
        schedulersQuery.include('details,values');
        schedulersQuery.limit('1000');
        schedulersQuery.index('values[Type],values[Name]');
        schedulersQuery.eq('values[Type]', 'TechBar');
        settingsQuery = new _react.SubmissionSearch(true);
        settingsQuery.include('details,values');
        settingsQuery.limit('1000');
        settingsQuery.index('values[Scheduler Id]:UNIQUE');
        _context.next = 11;
        return (0, _effects.select)(function (state) {
          return state.app.kappSlug;
        });
      case 11:
        kappSlug = _context.sent;
        _context.next = 14;
        return (0, _effects.all)([(0, _effects.call)(_react.searchSubmissions, {
          search: schedulersQuery.build(),
          datastore: true,
          form: _constants.SCHEDULER_FORM_SLUG
        }), (0, _effects.call)(_react.searchSubmissions, {
          search: settingsQuery.build(),
          datastore: true,
          form: _constants.TECH_BAR_SETTINGS_FORM_SLUG
        }), (0, _effects.call)(_react.fetchForms, {
          kappSlug: kappSlug,
          include: 'details,attributes'
        })]);
      case 14:
        _yield$all = _context.sent;
        _yield$all2 = (0, _slicedToArray2["default"])(_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 (0, _effects.put)(_techBarApp.actions.fetchAppDataFailure(schedulersError || settingsError || formsError));
      case 28:
        (0, _bundleCommon.addToastAlert)({
          title: 'Failed to load Tech Bar App.',
          message: (schedulersError || settingsError || formsError).message
        });
        _context.next = 33;
        break;
      case 31:
        _context.next = 33;
        return (0, _effects.put)(_techBarApp.actions.fetchAppDataSuccess({
          schedulers: schedulers.map(function (scheduler) {
            return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, scheduler), {}, {
              settings: (0, _techBarApp.Settings)(techBarSettings.find(function (s) {
                return s.values['Scheduler Id'] === scheduler.values['Id'];
              }))
            });
          }),
          forms: forms
        }));
      case 33:
      case "end":
        return _context.stop();
    }
  }, _marked);
}
function fetchDisplayTeamRequestSaga(_ref) {
  var techBarName = _ref.payload.techBarName;
  return /*#__PURE__*/(0, _regeneratorRuntime2["default"])().mark(function _callee() {
    var _yield$call, team, error;
    return (0, _regeneratorRuntime2["default"])().wrap(function _callee$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 2;
          return (0, _effects.call)(_react.fetchTeam, {
            teamSlug: (0, _md["default"])("Role::Tech Bar Display::".concat(techBarName)),
            include: 'attributes,memberships.user,memberships.user.attributes,memberships.user.profileAttributes'
          });
        case 2:
          _yield$call = _context2.sent;
          team = _yield$call.team;
          error = _yield$call.error;
          if (!error) {
            _context2.next = 10;
            break;
          }
          _context2.next = 8;
          return (0, _effects.put)(_techBarApp.actions.fetchDisplayTeamFailure(error));
        case 8:
          _context2.next = 12;
          break;
        case 10:
          _context2.next = 12;
          return (0, _effects.put)(_techBarApp.actions.fetchDisplayTeamSuccess(team));
        case 12:
        case "end":
          return _context2.stop();
      }
    }, _callee);
  })();
}
function createDisplayTeamMembershipRequestSaga(_ref2) {
  var _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;
  return /*#__PURE__*/(0, _regeneratorRuntime2["default"])().mark(function _callee2() {
    var toAdd, results, success, errorList;
    return (0, _regeneratorRuntime2["default"])().wrap(function _callee2$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          toAdd = username ? [username] : usernames;
          if (!(toAdd.length === 0)) {
            _context3.next = 4;
            break;
          }
          (0, _bundleCommon.addToast)({
            message: 'No users selected to add.',
            severity: 'danger'
          });
          return _context3.abrupt("return");
        case 4:
          _context3.next = 6;
          return (0, _effects.all)(toAdd.map(function (u) {
            return (0, _effects.call)(_react.createMembership, {
              team: {
                name: "Role::Tech Bar Display::".concat(techBarName)
              },
              user: {
                username: u
              }
            });
          }));
        case 6:
          results = _context3.sent;
          success = false;
          errorList = results.reduce(function (errorList, _ref3) {
            var error = _ref3.error;
            if (error) {
              return [].concat((0, _toConsumableArray2["default"])(errorList), [error]);
            } else {
              success = true;
              return errorList;
            }
          }, []);
          if (errorList.length > 0) {
            (0, _bundleCommon.addToastAlert)({
              title: 'Error adding new users.',
              message: errorList.map(function (e) {
                return e.message;
              }).join('\n')
            });
          }
          if (!success) {
            _context3.next = 14;
            break;
          }
          (0, _bundleCommon.addToast)("User".concat(toAdd.length > 1 ? 's' : '', " added successfully."));
          _context3.next = 14;
          return (0, _effects.put)(_techBarApp.actions.fetchDisplayTeamRequest({
            techBarName: techBarName
          }));
        case 14:
        case "end":
          return _context3.stop();
      }
    }, _callee2);
  })();
}
function deleteDisplayTeamMembershipRequestSaga(_ref4) {
  var _ref4$payload = _ref4.payload,
    username = _ref4$payload.username,
    techBarName = _ref4$payload.techBarName;
  return /*#__PURE__*/(0, _regeneratorRuntime2["default"])().mark(function _callee3() {
    var _yield$call2, error;
    return (0, _regeneratorRuntime2["default"])().wrap(function _callee3$(_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          _context4.next = 2;
          return (0, _effects.call)(_react.deleteMembership, {
            teamSlug: (0, _md["default"])("Role::Tech Bar Display::".concat(techBarName)),
            username: username
          });
        case 2:
          _yield$call2 = _context4.sent;
          error = _yield$call2.error;
          if (!error) {
            _context4.next = 8;
            break;
          }
          (0, _bundleCommon.addToastAlert)({
            title: 'Error removing user.',
            message: error.message
          });
          _context4.next = 11;
          break;
        case 8:
          (0, _bundleCommon.addToast)("User was removed successfully.");
          _context4.next = 11;
          return (0, _effects.put)(_techBarApp.actions.fetchDisplayTeamRequest({
            techBarName: techBarName
          }));
        case 11:
        case "end":
          return _context4.stop();
      }
    }, _callee3);
  })();
}
function createDisplayTeamUserRequestSaga(_ref5) {
  var _ref5$payload = _ref5.payload,
    user = _ref5$payload.user,
    teamName = _ref5$payload.teamName,
    techBarName = _ref5$payload.techBarName;
  return /*#__PURE__*/(0, _regeneratorRuntime2["default"])().mark(function _callee4() {
    var _yield$call3, error;
    return (0, _regeneratorRuntime2["default"])().wrap(function _callee4$(_context5) {
      while (1) switch (_context5.prev = _context5.next) {
        case 0:
          _context5.next = 2;
          return (0, _effects.call)(_react.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 2:
          _yield$call3 = _context5.sent;
          error = _yield$call3.error;
          if (!error) {
            _context5.next = 8;
            break;
          }
          (0, _bundleCommon.addToastAlert)({
            title: 'Error creating user.',
            message: error.message
          });
          _context5.next = 11;
          break;
        case 8:
          (0, _bundleCommon.addToast)("User was created successfully.");
          _context5.next = 11;
          return (0, _effects.put)(_techBarApp.actions.fetchDisplayTeamRequest({
            techBarName: techBarName
          }));
        case 11:
        case "end":
          return _context5.stop();
      }
    }, _callee4);
  })();
}
function watchTechBarApp() {
  return (0, _regeneratorRuntime2["default"])().wrap(function watchTechBarApp$(_context6) {
    while (1) switch (_context6.prev = _context6.next) {
      case 0:
        _context6.next = 2;
        return (0, _effects.takeEvery)(_techBarApp.types.FETCH_APP_DATA_REQUEST, fetchAppDataRequestSaga);
      case 2:
        _context6.next = 4;
        return (0, _effects.takeEvery)(_techBarApp.types.FETCH_DISPLAY_TEAM_REQUEST, fetchDisplayTeamRequestSaga);
      case 4:
        _context6.next = 6;
        return (0, _effects.takeEvery)(_techBarApp.types.CREATE_DISPLAY_TEAM_MEMBERSHIP_REQUEST, createDisplayTeamMembershipRequestSaga);
      case 6:
        _context6.next = 8;
        return (0, _effects.takeEvery)(_techBarApp.types.DELETE_DISPLAY_TEAM_MEMBERSHIP_REQUEST, deleteDisplayTeamMembershipRequestSaga);
      case 8:
        _context6.next = 10;
        return (0, _effects.takeEvery)(_techBarApp.types.CREATE_DISPLAY_TEAM_USER_REQUEST, createDisplayTeamUserRequestSaga);
      case 10:
      case "end":
        return _context6.stop();
    }
  }, _marked2);
}