<?php

declare(strict_types=1);

namespace App\Handler\Api;

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

class JudgeImageHandler extends AbstractCrudHandler
{
    const IDENTIFIER_NAME = 'slug';

    /** @var JudgeManager */
    private $judgeManager;

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

    /**
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function get(ServerRequestInterface $request): ResponseInterface
    {
        $slug = $request->getAttribute(static::IDENTIFIER_NAME);
        $imageResponse = new TextResponse($this->judgeManager->getProfileImage($slug));
        return $imageResponse
          ->withHeader('Content-Type', 'image/jpeg')
          ->withHeader('Cache-Control', 'must-revalidate')
        ;
    }

    /**
     * @param ServerRequestInterface $request
     * @return JsonResponse
     */
    public function create(ServerRequestInterface $request): ResponseInterface
    {
        $slug = $request->getAttribute(static::IDENTIFIER_NAME);
        /** @var UploadedFileInterface[] $files */
        $files = $request->getUploadedFiles();
        $imageData = $files['image']->getStream()->getContents();
        $entity = $this->judgeManager->setProfileImage($slug, $imageData);
        return new JsonResponse($entity);
    }

    /**
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function delete(ServerRequestInterface $request): ResponseInterface
    {
        $slug = $request->getAttribute(static::IDENTIFIER_NAME);
        return new JsonResponse($this->judgeManager->deleteProfileImage($slug));
    }
}
