<?php
namespace App\Controller\Api;
use App\Entity\Category;
use App\Entity\Material;
use App\Entity\Customer;
use App\Entity\Exercise;
use App\Entity\ExerciseCalendar;
use App\Entity\ExerciseQualification;
use App\Entity\ExerciseTranslation;
use App\Entity\ExerciseUser;
use App\Entity\PlayerJustification;
use App\Entity\TrainingAsist;
use App\Services\Api\ExerciseManager;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints\Date;
use Symfony\Contracts\Translation\TranslatorInterface;
class ExerciseController extends ApiController
{
/** @var ExerciseManager $exerciseManager */
protected $exerciseManager;
/**
* @param ExerciseManager $exerciseManager
*/
public function __construct(EntityManagerInterface $em, ParameterBagInterface $parameterBag, ExerciseManager $exerciseManager)
{
parent::__construct($em, $parameterBag);
$this->exerciseManager = $exerciseManager;
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/list", name="api_exercise_list", methods={"POST"})
*/
public function listExercise(Request $request)
{
$request = $this->transformJsonBody($request);
$exercises = [];
$prefixFile = $this->getParameter("app.path.exercise_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$exercises_user = $this->em->getRepository(ExerciseUser::class)->findBy([
'user_id' => $customer->getId(),
]);
/** @var Exercise $exercise */
foreach ($exercises_user as $exercise) {
$exercises[] = $exercise->__toArray($baseurl . $prefixFile . "/");
}
}
return $this->response($exercises);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/add", name="api_exercise_add", methods={"POST"})
*/
public function addExercise(Request $request)
{
$request = $this->transformJsonBody($request);
$data = $this->getDataForAddFromRequest($request);
// if ($request->get('is_customer')) {
// $data['customerId'] = $this->getUser()->getId();
//}
if ($request->get('is_customer')) {
if ($request->get('customerId')) {
$data['customerId'] = $request->get('customerId');
} else {
$data['customerId'] = $this->getUser()->getId();
}
}
$response = $this->exerciseManager->addExercise($data, $request);
if ($response['code'] == 200) {
$prefixFile = $this->getParameter("app.path.exercise_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$response['exercise'] = $response['exercise']->__toArray($baseurl . $prefixFile . "/");
}
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/user/list", name="api_exercise_user_list", methods={"POST"})
*/
public function listExerciseUser(Request $request)
{
$request = $this->transformJsonBody($request);
$exercises = [];
$prefixFile = $this->getParameter("app.path.exercise_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
/** @var Customer $customer */
$customer = $this->getUser();
$urlImages = $baseurl . $prefixFile . "/";
$response = $this->exerciseManager->list($customer, $urlImages);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/shared", name="api_exercise_shared_list", methods={"POST"})
*/
public function listExerciseShared(Request $request)
{
$request = $this->transformJsonBody($request);
$prefixFile = $this->getParameter("app.path.exercise_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
/** @var Customer $customer */
$customer = $this->getUser();
$urlImages = $baseurl . $prefixFile . "/";
$exercises = $this->exerciseManager->listShared($customer, $urlImages);
return $this->response($exercises);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/shared/public", name="api_exercise_shared_public_list", methods={"POST"})
*/
public function listExerciseSharedPublic(Request $request)
{
$request = $this->transformJsonBody($request);
$prefixFile = $this->getParameter("app.path.exercise_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$urlImages = $baseurl . $prefixFile . "/";
$exercises = $this->exerciseManager->listSharedAll($urlImages);
return $this->response($exercises);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/delete/{exercise}", name="api_exercise_delete", methods={"POST"})
*/
public function deleteExercise(Exercise $exercise)
{
/** @var Customer $customer */
$prefixFile = $this->getParameter("app.path.exercise_images");
$customer = $this->getUser();
$response = $this->exerciseManager->deleteExercise($exercise, $prefixFile);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/categories", name="api_exercise_categories", methods={"POST"})
*/
public function exerciseCategories(Request $request)
{
$prefixFile = $this->getParameter("app.path.exercise_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$categories = [];
/** @var Category $cat */
foreach ($this->em->getRepository(Category::class)->findAll() as $cat) {
$categories[] = $cat->__toArray($baseurl . $prefixFile . "/");
}
return $this->response($categories);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/materials", name="api_exercise_materials", methods={"POST"})
*/
public function exerciseMaterials(Request $request)
{
$materials = [];
/** @var Material $cat */
foreach ($this->em->getRepository(Material::class)->findAll() as $mat) {
$materials[] = $mat->__toArray();
}
return $this->response($materials);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/search", name="api_exercises_by_search", methods={"POST"})
*/
public function exercisesBySearch(Request $request, TranslatorInterface $i18n)
{
$prefixFile = $this->getParameter("app.path.exercise_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$request = $this->transformJsonBody($request);
$criteria = ["search" => $request->get('search')];
$exercises = [];
/** @var ExerciseTranslation $exerciseTranslation */
/** @var Exercise $exercise */
$exerciseRepo = $this->em->getRepository(Exercise::class);
$customer_id = $this->getUser()->getId();
$exercisesWithUser = $exerciseRepo->createQueryBuilder('e')
->where("e.customer_id IS NULL or e.customer_id = '$customer_id'")
->getQuery()
->getResult();
foreach ($exercisesWithUser as $exe) {
$exerciseId = $exe->getTranslatableId();
$exercise = (!empty($exerciseId)) ? $exerciseRepo->find($exerciseId) : null;
if (!empty($exercise)) {
$data = [
"id" => $exercise->getId(),
"name" => $exe->getName(),
"description" => $exe->getDescription(),
"categoryId" => $exe->getCategory() ? $exe->getCategory()->getId() : null,
"image" => !empty($exercise->getImage()) ? $baseurl . $prefixFile . "/" . $exercise->getImage() : "",
"poster" => !empty($exercise->getPoster()) ? $baseurl . $prefixFile . "/" . $exercise->getPoster() : "",
"dificulty" => $exercise->getDificulty(),
"intensity" => $exercise->getIntensity(),
"duration" => $exercise->getDuration(),
"materials" => $exercise->getMaterialsArray(),
];
} else {
$exercise = $exerciseRepo->find($exe->getId());
$data[] = $exercise->__toArray($baseurl . $prefixFile . "/");
}
$exercises[] = $data;
}
return $this->response($exercises);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/exercises/{category}", name="api_exercises_by_category", methods={"POST"})
*/
public function exercisesByCategories($category, Request $request)
{
$prefixFile = $this->getParameter("app.path.exercise_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$filter = ["category" => $category];
$exercises = [];
/** @var Exercise $exe */
foreach ($this->em->getRepository(Exercise::class)->findBy($filter) as $exe) {
$exercises[] = [
"id" => $exe->getId(),
"image" => !empty($exe->getImage()) ? $baseurl . $prefixFile . "/" . $exe->getImage() : "",
"poster" => !empty($exe->getPoster()) ? $baseurl . $prefixFile . "/" . $exe->getPoster() : "",
"name" => $exe->getName(),
"duaration" => $exe->getDuration(),
];
}
return $this->response($exercises);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/data/{exerciseId}", name="api_exercise_by_id", methods={"POST"})
*/
public function exerciseById($exerciseId, Request $request, TranslatorInterface $i18n)
{
$prefixFile = $this->getParameter("app.path.exercise_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
/** @var Exercise $exercise */
$exercise = $this->em->getRepository(Exercise::class)->find($exerciseId);
if (!empty($exercise)) {
$exercise = $exercise->__toArray($baseurl . $prefixFile . "/");
$exercise["dificulty"] = $i18n->trans("label." . $exercise["dificulty"]);
$exercise["intensity"] = $i18n->trans("label." . $exercise["intensity"]);
} else {
$exercise = [];
}
return $this->response($exercise);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/edit/{exercise}", name="api_exercise_edit", methods={"POST"})
*/
public function exerciseEdit(Exercise $exercise, Request $request)
{
$request = $this->transformJsonBody($request);
$data = $this->getDataFromRequest($request);
$response = $this->exerciseManager->edit($exercise, $data);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/update/{id}", name="api_exercise_update", methods={"POST"})
*/
public function exerciseUpdate($id, Request $request)
{
$request = $this->transformJsonBody($request);
$data = $this->getDataForAddFromRequest($request);
$response = $this->exerciseManager->updateExercise($id, $data, $request);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
protected function getDataForAddFromRequest(Request $request)
{
if ($request->get('categoryId')) {
$category = $this->em->getRepository(Category::class)->find($request->get('categoryId'));
if (!$category) {
$category = $this->em->getRepository(Category::class)->findAll()[0];
}
} else {
$category = $this->em->getRepository(Category::class)->findAll()[0];
}
$data = [
"title" => $request->get('title'),
"description" => $request->get('description'),
"image" => $request->files->get('image'),
"material" => $request->get('material'),
"dificulty" => $request->get('dificulty'),
"intensity" => $request->get('intensity'),
"duration" => $request->get('duration'),
"category" => $category,
];
return $data;
}
protected function getDataFromRequest(Request $request)
{
$data = [
"duration" => $request->get('duration')
];
return $data;
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/calendars/{date}", name="api_exercise_calendars", methods={"POST"})
*/
public function getCalendarExercises(DateTime $date)
{
$date = new \DateTime($date->format('Y-m-d H:i:s'));
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
$filter = [
[
"prop" => "season",
"comp" => "=",
"val" => $season->getId()
],
[
"prop" => "date",
"comp" => ">=",
"val" => $date->format('Y-m') . '-01'
],
[
"prop" => "date",
"comp" => "<=",
"val" => $date->format('Y-m-t')
],
];
// se suman los tiempos de los ejercicios
$listExercises = [];
/** @var ExerciseCalendar $exerciseCalendar */
foreach ($this->em->getRepository(ExerciseCalendar::class)->findByOwnCriteria($filter) as $key => $exerciseCalendar) {
if (isset($listExercises[$exerciseCalendar->getDate()->format("Y-m-d")])) {
$listExercises[$exerciseCalendar->getDate()->format("Y-m-d")] += is_null($exerciseCalendar->getExercise()) ? 0 : $exerciseCalendar->getExercise()->getDuration();
}
if (!isset($listExercises[$exerciseCalendar->getDate()->format("Y-m-d")])) {
$listExercises[$exerciseCalendar->getDate()->format("Y-m-d")] = is_null($exerciseCalendar->getExercise()) ? 0 : $exerciseCalendar->getExercise()->getDuration();
}
}
$trainingsAsists = $this->em->getRepository(TrainingAsist::class)->findByOwnCriteria($filter, [
'sort' => 'date',
'dir' => 'asc'
]);
$list = [];
foreach ($trainingsAsists as $key => $value) {
$data = $value->__toArrayWithPlayers();
$data['exercise_duration'] = isset($listExercises[$data['date']]) ? $listExercises[$data['date']] : 0;
if ($data['exercise_duration'] || count($data['players'])) {
$list[] = $data;
} else {
$deleteAsist = $this->em->getRepository(TrainingAsist::class)->find($data['id']);
if ($deleteAsist) {
$this->em->remove($deleteAsist);
$this->em->flush();
}
}
}
// eliminar ejericios sobrantes
return $this->response($list);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/calendar/{month}", name="api_exercise_calendar", methods={"POST"})
*/
public function calendarExercises($month)
{
$exercises = [];
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
[
"prop" => "season",
"comp" => "=",
"val" => $season->getId()
],
[
"prop" => "date",
"comp" => ">=",
"val" => \DateTime::createFromFormat("dd/m/Y", "01/" . ($month) . "/" . date('Y'))
],
[
"prop" => "date",
"comp" => "<=",
"val" => \DateTime::createFromFormat("d/m/Y", "31/" . ($month) . "/" . date('Y'))
],
];
/** @var ExerciseCalendar $exerciseCalendar */
foreach ($this->em->getRepository(ExerciseCalendar::class)->findByOwnCriteria($filter) as $exerciseCalendar) {
$exercises[] = [
"id" => $exerciseCalendar->getId(),
"date" => $exerciseCalendar->getDate()->format("Y-m-d"),
"exercise_duration" => $exerciseCalendar->getExercise()->getDuration()
];
}
}
return $this->response($exercises);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/calendar/{date}/get", name="api_exercise_calendar_get", methods={"POST"})
*/
public function calendarExercisesGet($date, Request $request)
{
$exercises = [];
$prefixFile = $this->getParameter("app.path.exercise_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
'season' => $season->getId(),
'date' => \DateTime::createFromFormat("d-m-Y", $date),
];
/** @var ExerciseCalendar $exerciseCalendar */
foreach ($this->em->getRepository(ExerciseCalendar::class)->findBy($filter) as $exerciseCalendar) {
$exercise = $exerciseCalendar->getExercise();
$exercises[] = [
"id" => $exercise->getId(),
"image" => !empty($exercise->getImage()) ? $baseurl . $prefixFile . "/" . $exercise->getImage() : "",
"poster" => !empty($exercise->getPoster()) ? $baseurl . $prefixFile . "/" . $exercise->getPoster() : "",
"name" => $exercise->getName(),
"categoryId" => $exercise->getCategory() ? $exercise->getCategory()->getId() : null,
"duration" => $exercise->getDuration(),
"customer" => $exercise->getCustomerId(),
];
}
}
return $this->response($exercises);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/calendar/{date}/add", name="api_exercise_calendar_add", methods={"POST"})
*/
public function calendarExerciseAdd($date, Request $request)
{
$request = $this->transformJsonBody($request);
$exercise = $request->get('exercise');
$data = [
'date' => $date,
'exercise' => $exercise,
'type' => $request->get('type'),
];
$response = $this->exerciseManager->addCalendar($data);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/calendar/{date}/remove", name="api_exercise_calendar_remove", methods={"POST"})
*/
public function calendarExerciseRemove($date, Request $request)
{
$request = $this->transformJsonBody($request);
$exercise = $request->get('exercise');
$data = [
'date' => $date,
'exercise' => $exercise,
];
$response = $this->exerciseManager->removeCalendar($data, $request);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/{exerciseId}/shared", name="api_exercise_shared", methods={"POST"})
*/
public function sharedExercise($exerciseId, Request $request)
{
$request = $this->transformJsonBody($request);
$isShared = $request->get('isShared');
$response = $this->exerciseManager->shared($request, $exerciseId, $isShared);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/exercise/{exerciseId}/qualification", name="api_exercise_add_qualification", methods={"POST"})
*/
public function exerciseQualification($exerciseId, Request $request)
{
$request = $this->transformJsonBody($request);
$quantity = $request->get('quantity');
$response = $this->exerciseManager->addQualification($exerciseId, $quantity);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
}