import _regeneratorRuntime from "@babel/runtime/regenerator";

var _initialState;

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); }); }; }

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); }

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
import { format, subMinutes, formatISO } from 'date-fns';
import { v4 } from 'uuid';

var createOrValidateIdentifier = function createOrValidateIdentifier() {
  var identifierLocalStorage = localStorage.getItem('identifier');
  if (identifierLocalStorage) return identifierLocalStorage;
  var identifier = v4();
  localStorage.setItem('identifier', identifier);
  return identifier;
};

var createAndValidateSession = function createAndValidateSession(IsNew) {
  if (IsNew === void 0) {
    IsNew = false;
  }

  if (IsNew) {
    localStorage.setItem('lastSession', localStorage.getItem('session'));
    localStorage.removeItem('session');
  }

  var newSession = {
    id: v4(),
    lastUpdate: formatISO(new Date())
  };
  var session = JSON.parse(localStorage.getItem('session')) || newSession;
  var date = formatISO(subMinutes(new Date(), 5));
  var storageDate = session.lastUpdate;
  session = date < storageDate ? _extends({}, session, {
    lastUpdate: formatISO(new Date())
  }) : newSession;
  localStorage.setItem('session', JSON.stringify(session));
  return session;
};

export var getPrintScreen = function getPrintScreen() {
  var canvas = document.getElementById('canvas');
  var oCtx = canvas.getContext('2d');
  oCtx.beginPath();
  oCtx.moveTo(0, 0);
  oCtx.lineTo(300, 150);
  oCtx.stroke();
  return canvas.toDataURL();
};
export var getPhysicalAssessmentsMetrics = createAsyncThunk('getPhysicalAssessmentsMetrics', /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(body) {
    var startDate, finalDate, identifierUser, _yield$axios$get, data;

    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            startDate = format(new Date(body.rangeDate.start), 'yyyy-MM-dd');
            finalDate = format(new Date(body.rangeDate.end), 'yyyy-MM-dd');
            identifierUser = body.user ? "&user=" + body.user : "&identifier=" + body.identifier;
            _context.next = 6;
            return axios.get("/coach/physical-assessments/" + startDate + "/" + finalDate + "?exercise=" + body.exercise + identifierUser);

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

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

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

  return function (_x) {
    return _ref.apply(this, arguments);
  };
}());
export var fetchExercises = createAsyncThunk('fetchExercises', /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
  var _yield$axios$get2, data;

  return _regeneratorRuntime.wrap(function _callee2$(_context2) {
    while (1) {
      switch (_context2.prev = _context2.next) {
        case 0:
          _context2.prev = 0;
          _context2.next = 3;
          return axios.get('/coach/exercises');

        case 3:
          _yield$axios$get2 = _context2.sent;
          data = _yield$axios$get2.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]]);
})));
export var savePhysicalAssessmentsMetrics = createAsyncThunk('savePhysicalAssessmentsMetrics', /*#__PURE__*/function () {
  var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(body) {
    var _yield$axios$post, data;

    return _regeneratorRuntime.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            _context3.next = 3;
            return axios.post('/coach/physical-assessments', body);

          case 3:
            _yield$axios$post = _context3.sent;
            data = _yield$axios$post.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 (_x2) {
    return _ref3.apply(this, arguments);
  };
}());
export var deleteAssessmentImage = createAsyncThunk('deleteAssessmentImage', /*#__PURE__*/function () {
  var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(id) {
    var _yield$axios$delete, data;

    return _regeneratorRuntime.wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return axios["delete"]("/coach/physical-assessments/" + id);

          case 3:
            _yield$axios$delete = _context4.sent;
            data = _yield$axios$delete.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 (_x3) {
    return _ref4.apply(this, arguments);
  };
}());
var transtionsList = ['intro', 'readySetGo', 'closing', 'singleResult', 'openning'];
var initialState = (_initialState = {
  user: null,
  identifier: createOrValidateIdentifier(),
  session: createAndValidateSession(),
  // string
  lastSession: JSON.parse(localStorage.getItem('lastSession')) || null,
  exercises: [],
  // array object
  currentExercise: {},
  // object
  goToExercise: null,
  pose: {
    angleResult: 0
  },
  bodyPartsNotVisible: {
    part1: null,
    part2: null,
    part3: null
  },
  progress: {
    total: 0,
    // numero de exercícios
    completed: 0,
    current: 0
  },
  gallery: {
    isOpened: false,
    images: [],
    imagesToCompare: [],
    rangeDate: {
      start: formatISO(new Date()),
      end: formatISO(new Date())
    }
  },
  tutorial: {
    watched: JSON.parse(localStorage.getItem('watchedTutorial')) || false,
    isOpened: false
  },
  splash: {
    isOpened: true
  },
  assessment: {
    isOpened: false
  },
  weeklyAssessment: {
    isOpened: false
  },
  menu: {
    isOpened: false
  }
}, _initialState["splash"] = {
  isOpened: true
}, _initialState.paused = true, _initialState.currentTransition = -1, _initialState.resultsExercises = [], _initialState.finishedExercises = {
  finished: false,
  isOpened: false
}, _initialState.loading = true, _initialState.isRepetingExercise = false, _initialState.aspectArea = {
  width: 1280,
  height: 720
}, _initialState);
export var main = createSlice({
  name: 'main',
  initialState: initialState,
  reducers: {
    updateUser: function updateUser(state, action) {
      state.user = action.payload || null;
    },
    startDateRange: function startDateRange(state, action) {
      state.gallery.rangeDate.start = action.payload;
    },
    endDateRange: function endDateRange(state, action) {
      state.gallery.rangeDate.end = action.payload;
    },
    goToGallery: function goToGallery(state, action) {
      state.paused = true;
      state.currentTransition = -1;
      state.gallery.isOpened = action.payload.isOpened;
      state.gallery.imagesToCompare = [];
      if (action.payload.exercise) state.currentExercise = _extends({}, action.payload.exercise);

      if (action.payload.isOpened) {
        state.gallery.images.map(function (img) {
          img.isSelected = false;
          return img;
        });
      }
    },
    goToAssessment: function goToAssessment(state, action) {
      state.weeklyAssessment.isOpened = false;
      state.splash.isOpened = false;
      state.assessment.isOpened = !state.assessment.isOpened;
      state.paused = state.assessment.isOpened;
      state.currentTransition = -1;
    },
    goToWeeklyAssessment: function goToWeeklyAssessment(state, action) {
      state.assessment.isOpened = false;
      state.splash.isOpened = false;
      state.weeklyAssessment.isOpened = !state.weeklyAssessment.isOpened;
      state.paused = state.weeklyAssessment.isOpened;
      state.currentTransition = -1;
    },
    watchTutorial: function watchTutorial(state, action) {
      state.tutorial.watched = action.payload;
      state.tutorial.isOpened = action.payload;
      state.paused = true;
      state.currentTransition = -1;
    },
    toggleTutorial: function toggleTutorial(state, action) {
      state.weeklyAssessment.isOpened = false;
      state.assessment.isOpened = false;
      state.splash.isOpened = false;
      state.tutorial.isOpened = action.payload;
      state.paused = state.tutorial.isOpened;
    },
    toggleSplash: function toggleSplash(state, action) {
      state.splash.isOpened = !state.splash.isOpened;
      state.paused = state.splash.isOpened;
    },
    togglePlayPause: function togglePlayPause(state, action) {
      state.paused = !state.paused;
    },
    nextTransition: function nextTransition(state, action) {
      var transition = -1;

      if (state.currentTransition === -1) {
        transition = 0;
      } else {
        var transitionIndex = transtionsList.findIndex(function (elm, index) {
          return index === state.currentTransition;
        });
        transition = transitionIndex === transtionsList.length - 1 ? -1 : transitionIndex + 1;
      }

      state.currentTransition = transition;
      state.paused = false;
    },
    goToExercise: function goToExercise(state, action) {
      state.gallery.isOpened = false;
      state.assessment.isOpened = false;
      state.weeklyAssessment.isOpened = false;
      state.paused = false;
      state.currentTransition = -1;
      state.isRepetingExercise = false;
      state.goToExercise = action.payload._id;
    },
    repetingExercise: function repetingExercise(state, action) {
      state.isRepetingExercise = action.payload;
      state.paused = false;
      state.currentTransition = 0;
    },
    nextExercise: function nextExercise(state, action) {
      var arr1 = state.exercises.map(function (exer) {
        return exer._id;
      });
      var arr2 = state.resultsExercises.map(function (exer) {
        return exer._id;
      });
      var diff = arr1.filter(function (x) {
        return !arr2.includes(x);
      });

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

      state.currentExercise = {};
      state.finishedExercises.finished = true;
      state.finishedExercises.isOpened = true;
      state.paused = true;
      state.isRepetingExercise = false;
    },
    resetResultsExercises: function resetResultsExercises(state, action) {
      state.resultsExercises = [];
      state.finishedExercises.finished = false;
      state.finishedExercises.isOpened = false;
      state.paused = false;
      state.currentTransition = -1;
    },
    exerciseValue: function exerciseValue(state, action) {
      state.pose.angleResult = action.payload;
    },
    getBodyPartsNotVisible: function getBodyPartsNotVisible(state, action) {
      state.bodyPartsNotVisible = action.payload;
    },
    toggleLoading: function toggleLoading(state, action) {
      state.loading = action.payload;
    },
    selectImagesToCompare: function selectImagesToCompare(state, action) {
      var index = action.payload;
      state.gallery.images[index].isSelected = state.gallery.imagesToCompare.length < 2 ? !state.gallery.images[index].isSelected : false;
      state.gallery.imagesToCompare = [].concat(state.gallery.images.filter(function (elm) {
        return elm.isSelected;
      }));
    },
    toggleMenu: function toggleMenu(state, action) {
      state.menu.isOpened = !state.menu.isOpened;
      state.paused = state.menu.isOpened ? true : false;
      state.currentTransition = -1;
      state.gallery.imagesToCompare = [];
    },
    updateAspectArea: function updateAspectArea(state, action) {
      state.aspectArea = _extends({}, state.aspectArea, action.payload);
    }
  },
  extraReducers: function extraReducers(builder) {
    builder.addCase(fetchExercises.fulfilled, function (state, action) {
      state.exercises = [].concat(action.payload);
      state.progress.total = state.exercises.length;
      state.resultsExercises = [];
    });
    builder.addCase(savePhysicalAssessmentsMetrics.pending, function (state, action) {
      var resultIndex = state.resultsExercises.findIndex(function (result) {
        var _action$meta, _action$meta$arg, _action$meta$arg$metr;

        return result._id === ((_action$meta = action.meta) === null || _action$meta === void 0 ? void 0 : (_action$meta$arg = _action$meta.arg) === null || _action$meta$arg === void 0 ? void 0 : (_action$meta$arg$metr = _action$meta$arg.metrics) === null || _action$meta$arg$metr === void 0 ? void 0 : _action$meta$arg$metr.exercise);
      });
      if (resultIndex !== -1) state.resultsExercises.splice(resultIndex, 1);
      state.resultsExercises.push(_extends({}, state.currentExercise, {
        result: action.meta.arg.metrics.value,
        printscreen: ''
      }));
    });
    builder.addCase(savePhysicalAssessmentsMetrics.fulfilled, function (state, action) {
      var resultIndex = state.resultsExercises.findIndex(function (result) {
        var _action$payload;

        return result._id === ((_action$payload = action.payload) === null || _action$payload === void 0 ? void 0 : _action$payload.metrics.exercise);
      });
      state.resultsExercises[resultIndex] = _extends({}, state.currentExercise, {
        result: action.payload.metrics.value,
        printscreen: action.payload.metrics.printscreen
      });

      if (state.resultsExercises.length === state.exercises.length) {
        state.finishedExercises.finished = true;
        state.finishedExercises.isOpened = true;
        state.paused = true;
        state.currentTransition = -1;
        state.session = createAndValidateSession(true);
        state.lastSession = JSON.parse(localStorage.getItem('lastSession'));
      }
    });
    builder.addCase(getPhysicalAssessmentsMetrics.fulfilled, function (state, action) {
      state.gallery.images = [];

      if (action.payload.length > 0) {
        var payload = [].concat(action.payload);
        var images = payload.map(function (elem) {
          return {
            _id: elem._id,
            exercise: elem.metrics.exercise,
            src: elem.metrics.printscreen,
            thumbnail: elem.metrics.printscreen,
            thumbnailWidth: 320,
            thumbnailHeight: 180,
            isSelected: false,
            date: format(new Date(elem.created_at), 'MM/dd/yyyy'),
            result: elem.metrics.value
          };
        });
        state.gallery.images = [].concat(images);
      }
    });
    builder.addCase(deleteAssessmentImage.fulfilled, function (state, action) {
      state.gallery.images = state.gallery.images.filter(function (image) {
        var _action$payload2;

        return image._id !== ((_action$payload2 = action.payload) === null || _action$payload2 === void 0 ? void 0 : _action$payload2._id);
      });
      state.resultsExercises = state.resultsExercises.filter(function (result) {
        var _action$payload3;

        return result._id !== ((_action$payload3 = action.payload) === null || _action$payload3 === void 0 ? void 0 : _action$payload3.metrics.exercise);
      });
    });
  }
}); // Action creators are generated for each case reducer function

var _main$actions = main.actions,
    updateUser = _main$actions.updateUser,
    startDateRange = _main$actions.startDateRange,
    endDateRange = _main$actions.endDateRange,
    goToExercise = _main$actions.goToExercise,
    goToGallery = _main$actions.goToGallery,
    goToAssessment = _main$actions.goToAssessment,
    watchTutorial = _main$actions.watchTutorial,
    toggleTutorial = _main$actions.toggleTutorial,
    toggleSplash = _main$actions.toggleSplash,
    togglePlayPause = _main$actions.togglePlayPause,
    toggleIntro = _main$actions.toggleIntro,
    toggleSingleResult = _main$actions.toggleSingleResult,
    toggleReadySetGo = _main$actions.toggleReadySetGo,
    toggleOpenning = _main$actions.toggleOpenning,
    toggleClosing = _main$actions.toggleClosing,
    nextTransition = _main$actions.nextTransition,
    resetResultsExercises = _main$actions.resetResultsExercises,
    nextExercise = _main$actions.nextExercise,
    exerciseValue = _main$actions.exerciseValue,
    getBodyPartsNotVisible = _main$actions.getBodyPartsNotVisible,
    toggleLoading = _main$actions.toggleLoading,
    selectImagesToCompare = _main$actions.selectImagesToCompare,
    toggleMenu = _main$actions.toggleMenu,
    goToWeeklyAssessment = _main$actions.goToWeeklyAssessment,
    repetingExercise = _main$actions.repetingExercise,
    updateAspectArea = _main$actions.updateAspectArea;
export { updateUser, startDateRange, endDateRange, goToExercise, goToGallery, goToAssessment, watchTutorial, toggleTutorial, toggleSplash, togglePlayPause, toggleIntro, toggleSingleResult, toggleReadySetGo, toggleOpenning, toggleClosing, nextTransition, resetResultsExercises, nextExercise, exerciseValue, getBodyPartsNotVisible, toggleLoading, selectImagesToCompare, toggleMenu, goToWeeklyAssessment, repetingExercise, updateAspectArea };
export default main.reducer;