<?php

namespace App\Controller;

use App\Entity\GradingGroup;
use App\Entity\Player;
use App\Entity\Score;
use App\Entity\User;
use App\Service\EvaluationService;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\PersistentCollection;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class EvaluationController extends Controller
{

    private $evaluationService;

    public function __construct(EvaluationService $evaluationService)
    {
        $this->evaluationService = $evaluationService;
    }

    /**
     * @Route("/evaluation", name="evaluation")
     */
    public function index()
    {

        $groups = $this->getPlayingGroups($this->getUser()->getGgroups());
        if(count($groups) == 1 && $groups[0] instanceof GradingGroup) {
            $player = $this->getDoctrine()->getRepository(Player::class)->findOneBy([
                'ggroup'=> $groups[0]->getId(),
                'status' => Player::STATUS_PLAYING,
            ]);
            if($player instanceof Player && !$this->isScoreSubmitted($player, $this->getUser())) {
                return $this->render('evaluation/details.html.twig', [
                    'player' => $player,
                ]);
            }
        }
        return $this->redirect('/');
    }

    private function isScoreSubmitted(Player $player, User $judge) {
        $scores = array_filter($player->getScores()->toArray(), function($score) use ($judge){
            return $score->getJudge() === $judge;
        });

        return count($scores) > 0;
    }
    private function getPlayingGroups($userGroups) {
        $filteredGroups = array_filter($userGroups->toArray(), function($group){
            return $group->getStatus() == GradingGroup::STATUS_PLAYING;
        });

        return array_values($filteredGroups);
    }

    /**
     * @Route("/evaluation/save", name="evaluationSave")
     */
    public function save(Request $request)
    {
        $paramTech = $request->request->get('tech-score');
        $playerId = $request->request->get('player');
        $isFraud = false;


        $em = $this->getDoctrine()->getManager();
        $player = $em->getRepository(Player::class)->find($playerId);

        if($this->isScoreSubmitted($player, $this->getUser())) {
            $this->addFlash(
                'error',
                'Fraudulent transaction'
            );
            $isFraud = true;
        }

        $this->evaluationService->createScoresFromParamsAndJudge([
            'id' => $playerId,
            'tech' => $paramTech,
            'isFraud' => $isFraud
        ], $this->getUser());

        $this->addFlash(
            'info',
            'Score submitted Successfully.'
        );

        return $this->redirect('/evaluation');
    }


}
