<?php

declare(strict_types=1);

namespace App\Handler\Api;

use App\Service\JudgeManager;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use UtilityModule\Handler\AbstractCrudHandler;
use Zend\Diactoros\Response\JsonResponse;

class JudgesHandler extends AbstractCrudHandler
{
    /** @var JudgeManager */
    private $judgeManager;

    public function __construct(
        JudgeManager $judgeManager
    ) {
        $this->judgeManager = $judgeManager;
    }

    /**
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function getList(ServerRequestInterface $request): ResponseInterface
    {
        $entities = $this->judgeManager->getJudges();
        return new JsonResponse($entities);
    }

    /**
     * @param ServerRequestInterface $request
     * @return JsonResponse
     */
    public function get(ServerRequestInterface $request): ResponseInterface
    {
        $id = $request->getAttribute(static::IDENTIFIER_NAME);
        $entity = $this->judgeManager->getJudge((int)$id);
        return new JsonResponse($entity);
    }

    /**
     * @param ServerRequestInterface $request
     * @return JsonResponse
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function create(ServerRequestInterface $request): ResponseInterface
    {
        $data = $this->getRequestData($request);
        $entity = $this->judgeManager->create($data);
        return new JsonResponse($entity);
    }

    /**
     * @param ServerRequestInterface $request
     * @return JsonResponse
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function update(ServerRequestInterface $request): ResponseInterface
    {
        $id = $request->getAttribute(static::IDENTIFIER_NAME);
        $data = $this->getRequestData($request);
        $entity = $this->judgeManager->update((int)$id, $data);
        return new JsonResponse($entity);
    }

    /**
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function delete(ServerRequestInterface $request): ResponseInterface
    {
        $id = $request->getAttribute(static::IDENTIFIER_NAME);
        return new JsonResponse($this->judgeManager->delete((int)$id));
    }
}
