<?php

declare(strict_types=1);

namespace App\Handler\Api;

use App\Service\AwardeeManager;
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 AwardeeImageHandler extends AbstractCrudHandler
{
    const IDENTIFIER_NAME = 'slug';

    /** @var AwardeeManager */
    private $awardeeManager;

    public function __construct(
        AwardeeManager $awardeeManager
    ) {
        $this->awardeeManager = $awardeeManager;
    }

    /**
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function get(ServerRequestInterface $request): ResponseInterface
    {
        $slug = $request->getAttribute(static::IDENTIFIER_NAME);
        $type = $request->getAttribute('type');
        $imageResponse = new TextResponse($this->awardeeManager->getProfileImage($slug, $type));
        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);
        $type = $request->getAttribute('type');
        /** @var UploadedFileInterface[] $files */
        $files = $request->getUploadedFiles();
        $imageData = $files['image']->getStream()->getContents();
        $entity = $this->awardeeManager->setProfileImage($slug, $imageData, $type);
        return new JsonResponse($entity);
    }

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