"use strict";

exports.__esModule = true;
exports.updateRecordConsult = exports.updateProps = exports.toggleMenu = exports.shouldRedirectTo = exports.shouldHideMenu = exports.savePhysioterapistVideo = exports.savePatientVideo = exports.savePatientEvaluation = exports.nextSequence = exports.nextExercise = exports.main = exports.invertVideo = exports.invertCam = exports.initSequence = exports.goToExercise = exports.fetchExercisesEffort = exports.fetchExercises = exports["default"] = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _toolkit = require("@reduxjs/toolkit");

var _axios = _interopRequireDefault(require("axios"));

var _uuid = require("uuid");

var _services = require("../../services");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

var savePhysioterapistVideo = (0, _toolkit.createAsyncThunk)('rehab/savePhysioterapistVideo', /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee(body) {
    var _yield$axios$post, data;

    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return _axios["default"].post('/coach/rehab/exercises', body, {
              headers: {
                'Content-Type': 'multipart/form-data'
              },
              onUploadProgress: function onUploadProgress(progressEvent) {
                _services.EventEmitter.emit('UPLOAD_PROGRESS', Math.floor(100 * (progressEvent.loaded / progressEvent.total)));
              }
            });

          case 3:
            _yield$axios$post = _context.sent;
            data = _yield$axios$post.data;
            return _context.abrupt("return", data);

          case 8:
            _context.prev = 8;
            _context.t0 = _context["catch"](0);
            return _context.abrupt("return", _context.t0.response);

          case 11:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 8]]);
  }));

  return function (_x) {
    return _ref.apply(this, arguments);
  };
}());
exports.savePhysioterapistVideo = savePhysioterapistVideo;
var savePatientVideo = (0, _toolkit.createAsyncThunk)('rehab/savePatientVideo', /*#__PURE__*/function () {
  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee2(body) {
    var _yield$axios$post2, data;

    return _regenerator["default"].wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.prev = 0;
            _context2.next = 3;
            return _axios["default"].post('/coach/rehab/exercises', body, {
              headers: {
                'Content-Type': 'multipart/form-data'
              },
              onUploadProgress: function onUploadProgress(progressEvent) {
                _services.EventEmitter.emit('UPLOAD_PROGRESS', Math.floor(100 * (progressEvent.loaded / progressEvent.total)));
              }
            });

          case 3:
            _yield$axios$post2 = _context2.sent;
            data = _yield$axios$post2.data;
            return _context2.abrupt("return", data);

          case 8:
            _context2.prev = 8;
            _context2.t0 = _context2["catch"](0);
            return _context2.abrupt("return", _context2.t0.response);

          case 11:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[0, 8]]);
  }));

  return function (_x2) {
    return _ref2.apply(this, arguments);
  };
}());
exports.savePatientVideo = savePatientVideo;
var savePatientEvaluation = (0, _toolkit.createAsyncThunk)('rehab/savePatientEvaluation', /*#__PURE__*/function () {
  var _ref3 = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee3(body) {
    var _yield$axios$post3, data;

    return _regenerator["default"].wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            _context3.next = 3;
            return _axios["default"].post('/coach/rehab/evaluations', body);

          case 3:
            _yield$axios$post3 = _context3.sent;
            data = _yield$axios$post3.data;
            return _context3.abrupt("return", data);

          case 8:
            _context3.prev = 8;
            _context3.t0 = _context3["catch"](0);
            return _context3.abrupt("return", _context3.t0.response);

          case 11:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 8]]);
  }));

  return function (_x3) {
    return _ref3.apply(this, arguments);
  };
}());
exports.savePatientEvaluation = savePatientEvaluation;
var fetchExercises = (0, _toolkit.createAsyncThunk)('fetchExercises', /*#__PURE__*/function () {
  var _ref4 = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee4(user) {
    var _yield$axios$get, data;

    return _regenerator["default"].wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return _axios["default"].get("/coach/rehab/" + user + "/exercises/list");

          case 3:
            _yield$axios$get = _context4.sent;
            data = _yield$axios$get.data;
            return _context4.abrupt("return", data);

          case 8:
            _context4.prev = 8;
            _context4.t0 = _context4["catch"](0);
            return _context4.abrupt("return", _context4.t0.response);

          case 11:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 8]]);
  }));

  return function (_x4) {
    return _ref4.apply(this, arguments);
  };
}());
exports.fetchExercises = fetchExercises;
var fetchExercisesEffort = (0, _toolkit.createAsyncThunk)('fetchExercisesEffort', /*#__PURE__*/function () {
  var _ref5 = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee5(user) {
    var _yield$axios$get2, data;

    return _regenerator["default"].wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            _context5.prev = 0;
            _context5.next = 3;
            return _axios["default"].get('/coach/exercises-effort');

          case 3:
            _yield$axios$get2 = _context5.sent;
            data = _yield$axios$get2.data;
            return _context5.abrupt("return", data);

          case 8:
            _context5.prev = 8;
            _context5.t0 = _context5["catch"](0);
            return _context5.abrupt("return", _context5.t0.response);

          case 11:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5, null, [[0, 8]]);
  }));

  return function (_x5) {
    return _ref5.apply(this, arguments);
  };
}());
exports.fetchExercisesEffort = fetchExercisesEffort;
var sequenceListPhysioretapist = ['recordConsult', 'recordVideo', 'resultRecordScreen'];
var sequenceListPatient = ['recordVideo', 'evaluationAssessment'];

var linkedList = function linkedList(arr) {
  return arr.reduceRight(function (next, value) {
    return {
      value: value,
      next: next
    };
  }, null);
};

var initialState = {
  user: null,
  sequence: null,
  recordConsult: {
    title: '',
    description: '',
    repetitions: null,
    setsPerSessions: null,
    setsPerDay: null,
    frequencyPerWeek: null,
    startDate: null,
    finalDate: null
  },
  completed: false,
  physioterapist: null,
  isPhysioterapist: false,
  exercises: [],
  exercisesEffort: [],
  exercisesCompleted: [],
  currentExercise: null,
  isMenuOpened: false,
  isHiddenMenu: true,
  identifier: (0, _uuid.v4)(),
  shouldRedirect: false,
  isInvertVideo: false,
  isInvertCam: false,
  progress: {
    total: 0,
    // numero de exercícios
    completed: 0,
    current: 0
  }
};
var main = (0, _toolkit.createSlice)({
  name: 'main',
  initialState: initialState,
  reducers: {
    initSequence: function initSequence(state, action) {
      state.sequence = linkedList(state.isPhysioterapist ? sequenceListPhysioretapist : sequenceListPatient);
      state.recordConsult = initialState.recordConsult;
      state.completed = initialState.completed;
      state.exercisesCompleted = initialState.exercisesCompleted;
      state.currentExercise = initialState.currentExercise;
      state.shouldRedirect = initialState.shouldRedirect;
      state.identifier = (0, _uuid.v4)();
    },
    nextSequence: function nextSequence(state, action) {
      state.sequence = action.payload;
    },
    updateProps: function updateProps(state, action) {
      var _action$payload;

      state.user = action.payload.user;
      state.physioterapist = (_action$payload = action.payload) === null || _action$payload === void 0 ? void 0 : _action$payload.physioterapist;
      state.isPhysioterapist = action.payload.isPhysioterapist;
      state.sequence = linkedList(action.payload.isPhysioterapist ? sequenceListPhysioretapist : sequenceListPatient);
    },
    goToExercise: function goToExercise(state, action) {
      state.currentExercise = action.payload;
    },
    nextExercise: function nextExercise(state, action) {
      var arr1 = state.exercises.map(function (exer) {
        return exer._id;
      });
      var arr2 = state.exercisesCompleted.map(function (exer) {
        return exer.exercise;
      });
      console.log('array 1:', arr1);
      console.log('Array 2:', arr2);
      var diff = arr1.filter(function (x) {
        return !arr2.includes(x);
      });

      if (diff.length > 0) {
        var exerciseIndex = state.exercises.findIndex(function (elm) {
          return state.currentExercise ? elm._id === state.currentExercise : elm._id === diff[0];
        });
        state.currentExercise = _extends({}, state.exercises[exerciseIndex]);
        state.progress.current = arr1.length - diff.length;
        state.progress.completed = state.progress.current * 100 / state.progress.total;
        return;
      }

      state.currentExercise = null;
    },
    updateRecordConsult: function updateRecordConsult(state, action) {
      state.recordConsult = action.payload;
    },
    toggleMenu: function toggleMenu(state, action) {
      state.isMenuOpened = !state.isMenuOpened;
    },
    invertVideo: function invertVideo(state, action) {
      state.isInvertVideo = !state.isInvertVideo;
    },
    invertCam: function invertCam(state, action) {
      state.isInvertCam = !state.isInvertCam;
    },
    shouldHideMenu: function shouldHideMenu(state, action) {
      state.isHiddenMenu = action.payload;
    },
    shouldRedirectTo: function shouldRedirectTo(state, action) {
      state.shouldRedirect = true;
    }
  },
  extraReducers: function extraReducers(builder) {
    builder.addCase(savePhysioterapistVideo.fulfilled, function (state, action) {
      state.completed = true;
    });
    builder.addCase(savePatientVideo.fulfilled, function (state, action) {
      state.exercisesCompleted = [].concat(state.exercisesCompleted, [action.payload]);
      state.completed = state.exercises.length === state.exercisesCompleted.length;
      state.isHiddenMenu = false;
      if (!state.completed) state.currentExercise = null;
    });
    builder.addCase(fetchExercises.fulfilled, function (state, action) {
      state.exercises = [].concat(action.payload);
      state.currentExercise = state.exercises[0];
      state.exercisesCompleted = [];
      state.isHiddenMenu = state.exercises.length === 0 ? true : false;
      state.progress.total = state.exercises.length;
    });
    builder.addCase(fetchExercisesEffort.fulfilled, function (state, action) {
      state.exercisesEffort = [].concat(action.payload);
    });
    builder.addCase(savePatientEvaluation.fulfilled, function (state, action) {
      state.shouldRedirect = true;
    });
  }
});
exports.main = main;
var _main$actions = main.actions,
    initSequence = _main$actions.initSequence,
    nextSequence = _main$actions.nextSequence,
    updateProps = _main$actions.updateProps,
    updateRecordConsult = _main$actions.updateRecordConsult,
    toggleMenu = _main$actions.toggleMenu,
    goToExercise = _main$actions.goToExercise,
    nextExercise = _main$actions.nextExercise,
    shouldHideMenu = _main$actions.shouldHideMenu,
    shouldRedirectTo = _main$actions.shouldRedirectTo,
    invertVideo = _main$actions.invertVideo,
    invertCam = _main$actions.invertCam;
exports.invertCam = invertCam;
exports.invertVideo = invertVideo;
exports.shouldRedirectTo = shouldRedirectTo;
exports.shouldHideMenu = shouldHideMenu;
exports.nextExercise = nextExercise;
exports.goToExercise = goToExercise;
exports.toggleMenu = toggleMenu;
exports.updateRecordConsult = updateRecordConsult;
exports.updateProps = updateProps;
exports.nextSequence = nextSequence;
exports.initSequence = initSequence;
var _default = main.reducer;
exports["default"] = _default;