<?php
namespace App\Services\Api;
use App\Entity\Competition;
use App\Entity\Convocatoria;
use App\Entity\ConvocatoriaPlayer;
use App\Entity\Customer;
use App\Entity\Difficulty;
use App\Entity\Game;
use App\Entity\Player;
use App\Entity\Minutes;
use App\Entity\YellowCards;
use App\Entity\RedCards;
use App\Entity\Goals;
use App\Entity\GoalAssistances;
use App\Entity\TrainingAsist;
use App\Entity\Titulars;
use App\Entity\PlayerJustification;
use App\Entity\GameAlignment;
use App\Entity\GamePlayerStatistics;
use App\Entity\JustificationType;
use App\Entity\KilometersTraveled;
use App\Entity\MediaGame;
use App\Entity\SeasonPlayer;
use App\Entity\ShotsOnGoal;
use App\Entity\Locality;
use Symfony\Component\Filesystem\Filesystem;
class GameManager extends BaseApiManager
{
public function add($data, $request)
{
$data = $this->runGoalVerifier($data);
$r = $this->validGame($data);
if ($r['code'] != 200)
return $r;
/** @var Customer $customer */
$customer = $this->security->getUser();
$season = $customer->getSeasonActive();
if (empty($season))
return [
"messageType" => "danger",
"message" => $this->translator->trans('msg.season_dont_active'),
"code" => 403
];
$game = new Game();
$game->setSeason($season);
$game = $this->setValues($game, $data);
if ($data['rivalTactic'] && $data['rivalPlayersFormation']) {
$rivalAlignment = new GameAlignment();
$rivalAlignment->setTactic($data['rivalTactic']);
$rivalAlignment->setAlignment($data['rivalPlayersFormation']);
$game->setRivalAlignment($rivalAlignment);
}
// locality
$locality = $this->em->getRepository(Locality::class)->find((int) $data['localityId']);
if ($locality) {
$game->setLocality($locality);
}
if (!$locality) {
$defaultLocality = $this->em->getRepository(Locality::class)->findOneBy([]);
if ($defaultLocality) {
$game->setLocality($defaultLocality);
}
}
// competition
$competition = $this->em->getRepository(Competition::class)->find((int) $data['competitionId']);
if ($competition) {
$game->setCompetition($competition);
}
if (!$competition) {
$defaultCompetition = $this->em->getRepository(Competition::class)->findOneBy([]);
if ($defaultCompetition) {
$game->setCompetition($defaultCompetition);
}
}
$this->em->persist($game);
$this->em->flush();
return [
"messageType" => "success",
"message" => $this->translator->trans('msg.game_add_success'),
"newGame" => $data,
'game' => $game,
"gameId" => $game->getId(),
"code" => 200
];
}
public function runGoalVerifier($data)
{
if (!isset($data["goals"]) || is_null($data["goals"])) {
$data["goals"] = "0";
}
if (!isset($data["category"]) || is_null($data["category"])) {
$data["category"] = 11;
}
if (!isset($data["timeMatch"]) || is_null($data["timeMatch"])) {
$data["timeMatch"] = 90;
}
if (!isset($data["rivalGoals"]) || is_null($data["rivalGoals"])) {
$data["rivalGoals"] = "0";
}
if (!isset($data["shotsGoal"]) || is_null($data["shotsGoal"])) {
$data["shotsGoal"] = "0";
}
if (!isset($data["shotsOpponent"]) || is_null($data["shotsOpponent"])) {
$data["shotsOpponent"] = "0";
}
if (!isset($data["cornersFavor"]) || is_null($data["cornersFavor"])) {
$data["cornersFavor"] = "0";
}
if (!isset($data["cornersAgainst"]) || is_null($data["cornersAgainst"])) {
$data["cornersAgainst"] = "0";
}
if (!isset($data["penaltiesFavor"]) || is_null($data["penaltiesFavor"])) {
$data["penaltiesFavor"] = "0";
}
if (!isset($data["penaltiesAgainst"]) || is_null($data["penaltiesAgainst"])) {
$data["penaltiesAgainst"] = "0";
}
if (!isset($data["foulsFavor"]) || is_null($data["foulsFavor"])) {
$data["foulsFavor"] = "0";
}
if (!isset($data["foulsAgainst"]) || is_null($data["foulsAgainst"])) {
$data["foulsAgainst"] = "0";
}
if (!isset($data["day"]) || is_null($data["day"]) || empty($data["day"])) {
$data["day"] = "1";
}
return $data;
}
public function edit($game, $data, $request)
{
$data = $this->runGoalVerifier($data);
$r = $this->validGame($data);
if ($r['code'] != 200)
return $r;
/** @var Customer $customer */
$customer = $this->security->getUser();
$season = $customer->getSeasonActive();
if (empty($season))
return [
"messageType" => "danger",
"message" => $this->translator->trans('msg.season_dont_active'),
"code" => 403
];
$filter = [
"season" => $season->getId(),
"id" => $game
];
/** @var Game $game */
$game = $this->em->getRepository(Game::class)->findOneBy($filter);
if (!empty($game)) {
$minutes_game_before = (int) $game->getTimeMatch();
$game = $this->setValues($game, $data);
if ($game->getRivalAlignment()) {
$rivalAlignment = $game->getRivalAlignment();
if ($data['rivalTactic'] && $data['rivalPlayersFormation']) {
$rivalAlignment->setTactic($data['rivalTactic']);
$rivalAlignment->setAlignment($data['rivalPlayersFormation']);
$game->setRivalAlignment($rivalAlignment);
} else {
$game->setRivalAlignment(null);
}
} else {
if ($data['rivalTactic'] && $data['rivalPlayersFormation']) {
$rivalAlignment = new GameAlignment();
$rivalAlignment->setTactic($data['rivalTactic']);
$rivalAlignment->setAlignment($data['rivalPlayersFormation']);
$game->setRivalAlignment($rivalAlignment);
}
}
/**
* Verifica minutos jugados por los jugadores segun el partido
*/
$minutes_game_after = (int) $game->getTimeMatch();
if ($minutes_game_before != $minutes_game_after) {
/**
* Valida y actualiza minutes players
*/
$criteria = [
"game" => $game
];
/** @var Minutes[] $obj_minutes */
/** @var Minutes $minutes */
$obj_minutes = $this->em->getRepository(Minutes::class)->findBy($criteria);
foreach ($obj_minutes as $_minutes) {
if ($_minutes) {
$minutes = $_minutes;
$edit_minutes = false;
$minutes_player = (int) $minutes->getQuantity();
if ($minutes_game_after < $minutes_player) {
$minutes->setQuantity($minutes_game_after);
$edit_minutes = true;
} elseif ($minutes_game_after > $minutes_player && $minutes_game_before === $minutes_player) {
$minutes->setQuantity($minutes_game_after);
$edit_minutes = true;
}
if ($edit_minutes) {
$this->em->persist($minutes);
}
}
}
}
$difficulty = $this->em->getRepository(Difficulty::class)->find((int) $data['pressureRivalId']);
if ($difficulty) {
$game->setPressureRival($difficulty);
}
$locality = $this->em->getRepository(Locality::class)->find((int) $data['localityId']);
if ($locality) {
$game->setLocality($locality);
}
$competition = $this->em->getRepository(Competition::class)->find((int) $data['competitionId']);
if ($competition) {
$game->setCompetition($competition);
}
$game->setOpponentCurrentPositionLeague((int) $data['opponentCurrentPositionLeague']);
$this->em->persist($game);
$this->em->flush();
}
return [
"messageType" => "success",
"message" => $this->translator->trans('msg.game_edit_success'),
"code" => 200
];
}
public function deleteGame(Game $game)
{
/** @var Customer $customer */
$customer = $this->security->getUser();
$season = $customer->getSeasonActive();
if (empty($season))
return [
"messageType" => "danger",
"message" => $this->translator->trans('msg.season_dont_active'),
"code" => 403
];
$game->setDeletedAt(new \DateTime('now'));
$this->em->persist($game);
$this->em->flush();
return [
"messageType" => "success",
"message" => $this->translator->trans('msg.game_delete_success'),
"code" => 200
];
}
public function restoreGame(Game $game){
/** @var Customer $customer */
$customer = $this->security->getUser();
$season = $customer->getSeasonActive();
if (empty($season))
return [
"messageType" => "danger",
"message" => $this->translator->trans('msg.season_dont_active'),
"code" => 403
];
$game->setDeletedAt(null);
$this->em->persist($game);
$this->em->flush();
return [
"messageType" => "success",
"message" => $this->translator->trans('msg.game_delete_success'),
"code" => 200
];
}
public function deleteGamePermanent(Game $game, string $urlFiles)
{
/** @var Customer $customer */
$customer = $this->security->getUser();
$season = $customer->getSeasonActive();
if (empty($season))
return [
"messageType" => "danger",
"message" => $this->translator->trans('msg.season_dont_active'),
"code" => 403
];
$counter = 0;
$criteria = [
"game" => $game
];
/** @var YellowCards $yellowCards */
foreach ($this->em->getRepository(YellowCards::class)->findBy($criteria) as $yellowCard) {
if ($yellowCard) {
$counter++;
$this->em->remove($yellowCard);
$this->em->flush();
}
}
/** @var Minutes $minutes */
foreach ($this->em->getRepository(Minutes::class)->findBy($criteria) as $minute) {
if ($minute) {
$counter++;
$this->em->remove($minute);
$this->em->flush();
}
}
/** @var RedCards $redCards */
foreach ($this->em->getRepository(RedCards::class)->findBy($criteria) as $redCard) {
if ($redCard) {
$counter++;
$this->em->remove($redCard);
$this->em->flush();
}
}
/** @var Goals $goals */
foreach ($this->em->getRepository(Goals::class)->findBy($criteria) as $goal) {
if ($goal) {
$counter++;
$this->em->remove($goal);
$this->em->flush();
}
}
/** @var GoalAssistances $goalAssistances */
foreach ($this->em->getRepository(GoalAssistances::class)->findBy($criteria) as $goalAssistance) {
if ($goalAssistance) {
$counter++;
$this->em->remove($goalAssistance);
$this->em->flush();
}
}
/** @var Titulars $titulars */
foreach ($this->em->getRepository(Titulars::class)->findBy($criteria) as $titulars) {
if ($titulars) {
$counter++;
$this->em->remove($titulars);
$this->em->flush();
}
}
/** @var KilometersTraveled $titulars */
foreach ($this->em->getRepository(KilometersTraveled::class)->findBy($criteria) as $kilometers) {
if ($kilometers) {
$counter++;
$this->em->remove($kilometers);
$this->em->flush();
}
}
/** @var ShotsOnGoal $titulars */
foreach ($this->em->getRepository(ShotsOnGoal::class)->findBy($criteria) as $shotsOnGoal) {
if ($shotsOnGoal) {
$counter++;
$this->em->remove($shotsOnGoal);
$this->em->flush();
}
}
/** @var GamePlayerStatistics $titulars */
foreach ($this->em->getRepository(GamePlayerStatistics::class)->findBy($criteria) as $gamePlayerStatistc) {
if ($gamePlayerStatistc) {
$this->em->remove($gamePlayerStatistc);
$this->em->flush();
}
}
/** @var MediaGame $titulars */
foreach ($this->em->getRepository(MediaGame::class)->findBy($criteria) as $mediaGame) {
if ($mediaGame) {
$media = $mediaGame->__toArray($urlFiles);
$fileSystem = new Filesystem();
$fileSystem->remove($media);
$this->em->remove($mediaGame);
$this->em->flush();
}
}
$this->em->remove($game);
$this->em->flush();
return [
"deleted" => $counter,
"messageType" => "success",
"message" => $this->translator->trans('msg.remove_game_permanent_success'),
"code" => 200
];
}
public function editLineUp($id, $lineup)
{
/** @var Customer $customer */
$customer = $this->security->getUser();
$season = $customer->getSeasonActive();
if (empty($season))
return [
"messageType" => "danger",
"message" => $this->translator->trans('msg.season_dont_active'),
"code" => 403
];
// foreach ($alignment as $playerId => $info) {
// /** @var SeasonPlayer $seasonPlayer */
// $seasonPlayer = $this->em->getRepository(SeasonPlayer::class)->find($playerId);
// $minutes = $seasonPlayer->getMinutes();
// $minutes = json_decode($minutes, true);
// $minutes[$id] = (int) $info->minutes;
// $minutes = json_encode($minutes);
// $seasonPlayer->setMinutes($minutes);
// $this->em->persist($seasonPlayer);
// $this->em->flush();
// }
/** @var Game $game */
$game = $this->em->getRepository(Game::class)->find($id);
$game->setLineup($lineup);
$this->em->persist($game);
$this->em->flush();
return [
"messageType" => "success",
"message" => $this->translator->trans('msg.alignment_success'),
"code" => 200
];
}
public function editAlignment($id, $alignment)
{
/** @var Customer $customer */
$customer = $this->security->getUser();
$season = $customer->getSeasonActive();
if (empty($season))
return [
"messageType" => "danger",
"message" => $this->translator->trans('msg.season_dont_active'),
"code" => 403
];
/** @var Game $game */
$game = $this->em->getRepository(Game::class)->find($id);
/** @var GameAlignment $gameAlignment */
$gameAlignment = $game->getAlignment();
if (isset($gameAlignment)) {
$gameAlignment->setTactic($alignment['tactic']);
$gameAlignment->setAlignment($alignment['alignment']);
} else {
$gameAlignment = new GameAlignment();
$gameAlignment->setTactic($alignment['tactic']);
$gameAlignment->setAlignment($alignment['alignment']);
$gameAlignment->setGame($game);
}
if(isset($alignment['captain'])){
$playerId = $alignment['captain'];
/** @var SeasonPlayer $seasonPlayer */
$seasonPlayer = $this->em->getRepository(SeasonPlayer::class)->findOneBy([
"season" => $game->getSeason(),
"player" => $playerId,
]);
$gameAlignment->setCaptain($seasonPlayer);
} else {
$gameAlignment->setCaptain(null);
}
$this->em->persist($gameAlignment);
$this->em->flush();
return [
"messageType" => "success",
"message" => $this->translator->trans('msg.alignment_success'),
"code" => 200
];
}
public function editConvocatoria($game, $players)
{
/** @var Customer $customer */
$customer = $this->security->getUser();
$season = $customer->getSeasonActive();
if (empty($season))
return [
"messageType" => "danger",
"message" => $this->translator->trans('msg.season_dont_active'),
"code" => 403
];
$filter = [
"season" => $season->getId(),
"id" => $game
];
/** @var Game $game */
$convocatoriaPlayerRepository = $this->em->getRepository(ConvocatoriaPlayer::class);
$game = $this->em->getRepository(Game::class)->findOneBy($filter);
if (!empty($game) && !empty($players)) {
/** @var Convocatoria $convocatoria */
$convocatoria = $game->getConvocatoria();
if (empty($convocatoria)) {
$convocatoria = new Convocatoria();
$convocatoria->setGame($game);
$this->em->persist($convocatoria);
$this->em->flush();
$this->em->clear();
$convocatoriaId = $convocatoria->getId();
} else {
$convocatoriaId = $convocatoria->getId();
$convocatoriaPlayers = $convocatoriaPlayerRepository->findBy([
'convocatoria_id' => $convocatoriaId,
]);
$convocatoria = $game->getConvocatoria();
/**
* SI NO ESTA EL JUGADOR EN LA CONVOCATORIA ENTRATE, SE ELIMINA
*/
foreach ($convocatoriaPlayers as $player) {
if (!in_array($player->getPlayerId(), array_column($players, 'id'))) {
$this->em->remove($player);
}
}
}
$playerRepository = $this->em->getRepository(Player::class);
foreach ($players as $p) {
/** @var Player $player */
$player = $playerRepository->find($p["id"]);
if ($player) {
/** @var ConvocatoriaPlayer $convocatoriaPlayer */
$convocatoriaPlayer = $convocatoriaPlayerRepository->findOneBy([
'player_id' => $p['id'],
'convocatoria_id' => $convocatoriaId,
]);
if (empty($convocatoriaPlayer)) {
$convocatoriaPlayer = new ConvocatoriaPlayer;
$convocatoriaPlayer->setPlayerId($p['id']);
$convocatoriaPlayer->setConvocatoriaId($convocatoriaId);
}
$isOn = true;
/** @var JustificationType $justificationType */
$justificationType = $this->em->getRepository(JustificationType::class)->find($p['justification_type']);
if (isset($p['is_active'])) {
//INPUT DE FORMDATA
$isOn = $p['is_active'];
// $justificationType = null;
if (intval($isOn) == 0 && intval($p['justification_type']) > 0) {
// $justificationType = $p['justification_type'];
}
}
}
$convocatoriaPlayer->setIsActive($isOn);
$convocatoriaPlayer->setJustificationType($justificationType);
$this->em->persist($convocatoriaPlayer);
}
}
$this->em->flush();
return [
"messageType" => "success",
"message" => $this->translator->trans('msg.convocatoria_success'),
"code" => 200
];
}
public function editTraining($date, $players)
{
/** @var Customer $customer */
$customer = $this->security->getUser();
$season = $customer->getSeasonActive();
if (empty($season))
return [
"messageType" => "danger",
"message" => $this->translator->trans('msg.season_dont_active'),
"code" => 403
];
$date = \DateTime::createFromFormat("d-m-Y", $date);
$filter = [
"season" => $season->getId(),
"date" => $date
];
/** @var Game $game */
$trainingAsist = $this->em->getRepository(TrainingAsist::class)->findOneBy($filter);
if (empty($trainingAsist)) {
$trainingAsist = new TrainingAsist();
$trainingAsist->setSeason($season)
->setDate($date);
}
if (!empty($players)) {
foreach ($players as $p) {
/** @var Player $player */
$player = $this->em->getRepository(Player::class)->find($p["id"]);
if (!empty($player)) {
if ($p["in"]) {
if (!$trainingAsist->getPlayers()->contains($player))
$trainingAsist->addPlayer($player);
} else {
if ($trainingAsist->getPlayers()->contains($player))
$trainingAsist->removePlayer($player);
}
if (isset($p['justification'])) {
$subfilter = [
"date" => $date,
"player" => $player->getId()
];
/** @var PlayerJustification $playerJustification */
$playerJustification = $this->em->getRepository(PlayerJustification::class)->findOneBy($subfilter);
/** @var JustificationType $justificationType */
$justificationType = $this->em->getRepository(JustificationType::class)->find($p['justification']['id']);
if (empty($playerJustification)) {
$playerJustification = new PlayerJustification();
$playerJustification->setJustificationType($justificationType);
$playerJustification->setPlayer($player);
$playerJustification->setIsActive(true);
$playerJustification->setDate($date);
$playerJustification->setSeason($season);
} else {
$playerJustification->setJustificationType($justificationType);
}
$this->em->persist($playerJustification);
$this->em->flush();
}
}
}
$this->em->persist($trainingAsist);
$this->em->flush();
}
return [
"messageType" => "success",
"message" => $this->translator->trans('msg.training_edit_success'),
"code" => 200
];
}
protected function validGame($data)
{
$code = 200;
$validates = [];
if (empty($data["rival"])) {
$code = 404;
$validates["rival"] = [
"type" => "error",
"msg" => "El nombre de rival es requerido",
"icon" => "glyphicon-warning-sign",
];
}
if (empty($data["localityId"])) {
$code = 404;
$validates["localityId"] = [
"type" => "error",
"msg" => "La localia es requerida",
"icon" => "glyphicon-warning-sign",
];
}
if (empty($data["day"])) {
$code = 404;
$validates["day"] = [
"type" => "error",
"msg" => "La jornada es requerida",
"icon" => "glyphicon-warning-sign",
];
}
if (empty($data["date"])) {
$code = 404;
$validates["date"] = [
"type" => "error",
"msg" => "La fecha es requerida",
"icon" => "glyphicon-warning-sign",
];
}
if (!isset($data["goals"]) || is_null($data["goals"])) {
$code = 404;
$validates["goals"] = [
"type" => "error",
"msg" => "Los goles son requeridos",
"icon" => "glyphicon-warning-sign",
];
}
if (!isset($data["rivalGoals"]) || is_null($data["rivalGoals"])) {
$code = 404;
$validates["rivalGoals"] = [
"type" => "error",
"msg" => "Los goles son requeridos",
"icon" => "glyphicon-warning-sign",
];
}
return [
"code" => $code,
"messageType" => "warning",
"message" => $this->translator->trans('msg.filed_requiered'),
"validates" => $validates
];
}
public function reconcileTitulars(Game $game)
{
/** @var GameAlignment $gameAlignment */
$gameAlignment = $game->getAlignment();
if ($gameAlignment) {
$alignments = json_decode((string) $gameAlignment->getAlignment());
if (JSON_ERROR_NONE !== json_last_error()) {
return false;
}
/** [[{id:0},{id:0}],[{id:0}]] */
foreach ($alignments as $alignment) {
/** [{id:0},{id:0}] */
foreach ($alignment as $player) {
if (isset($player['id']) && $player['id'] > 0) {
/** @var SeasonPlayer $seasonPlayer */
$seasonPlayer = $this->em->getRepository(SeasonPlayer::class)->find($player['id']);
$titular = $this->em->getRepository(Titulars::class)->findOneBy([
"seasonplayer" => $seasonPlayer,
"game" => $game
]);
if ($titular) {
$titular->setIsTitular(true);
$this->em->persist($titular);
}
}
}
}
$this->em->flush();
}
return true;
}
public function addGameCaptain($id, $playerId)
{
/** @var Customer $customer */
$customer = $this->security->getUser();
/** @var Game $game */
$game = $this->em->getRepository(Game::class)->find($id);
/** @var GameAlignment $gameAlignment */
$gameAlignment = $game->getAlignment();
/** @var SeasonPlayer $seasonPlayer */
$seasonPlayer = $this->em->getRepository(SeasonPlayer::class)->findOneBy([
"season" => $game->getSeason(),
"player" => $playerId,
]);
if (empty($seasonPlayer))
return [
"messageType" => "warning",
"message" => $this->translator->trans('msg.player_dont_exist'),
"code" => 404
];
if (isset($gameAlignment)) {
$gameAlignment->setCaptain($seasonPlayer);
} else {
$gameAlignment = new GameAlignment();
$gameAlignment->setTactic("");
$gameAlignment->setAlignment("");
$gameAlignment->setGame($game);
$gameAlignment->setCaptain($seasonPlayer);
}
$this->em->persist($gameAlignment);
$this->em->flush();
return [
"messageType" => "success",
"message" => $this->translator->trans('msg.alignment_success'),
"code" => 200
];
}
public function getGameCaptain($id)
{
/** @var Customer $customer */
$customer = $this->security->getUser();
$season = $customer->getSeasonActive();
if (empty($season))
return [
"messageType" => "danger",
"message" => $this->translator->trans('msg.season_dont_active'),
"code" => 403
];
/** @var Game $game */
$game = $this->em->getRepository(Game::class)->find($id);
/** @var GameAlignment $gameAlignment */
$gameAlignment = $game->getAlignment();
return [
"messageType" => "success",
"data" => [
'captainPlayerId' => $gameAlignment->getCaptain()->getPlayer()->getId(),
],
"message" => $this->translator->trans('msg.alignment_success'),
"code" => 200
];
}
}