<?php

namespace KupShop\CatalogBundle\Controller;

use KupShop\ContentBundle\Util\ImageLocator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;

class ImageController extends AbstractController
{
    /**
     * @Route("/data/tmp/{type}/{folder}/{image_id}_{type_img}_{version}.{lang}.{extension}", requirements={"type"="\d+", "type_img"="\d+", "folder"="\d", "image_id"="\d+", "version"="tablet|mobile", "lang"="[a-z]{2}"})
     * @Route("/data/tmp/{type}/{folder}/{image_id}_{type_img}_{version}.{extension}", requirements={"type"="\d+", "type_img"="\d+", "folder"="\d", "image_id"="\d+", "version"="tablet|mobile", "lang"="[a-z]{2}"})
     * @Route("/data/tmp/{type}/{folder}/{image_id}_{type_img}.{lang}.{extension}", requirements={"type"="\d+", "type_img"="\d+", "folder"="\d", "image_id"="\d+", "lang"="[a-z]{2}"})
     * @Route("/data/tmp/{type}/{folder}/{image_id}_{type_img}.{extension}", requirements={"type"="\d+", "type_img"="\d+", "folder"="\d", "image_id"="\d+"})
     * @Route("/photo/{type}/{image_id}/{img_title}.{version}", requirements={"image_id"="\d+", "version"="desktop|tablet|mobile"})
     * @Route("/photo/{type}/{image_id}/{img_title}.{version}.{lang}", requirements={"image_id"="\d+", "version"="desktop|tablet|mobile", "lang"="[a-z]{2}"})
     *
     * @param null $lang
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function thumbnailAction(Request $request, $image_id, $type, $lang = null, $version = null)
    {
        $imageClass = new \Image();

        try {
            $image = $imageClass->getImage($image_id, $type, $lang, $version);
            $image = $imageClass->createThumbnail($image);

            return $imageClass->outputImage($image);
        } catch (\UnexpectedValueException $e) {
            throw new NotFoundHttpException('Unknown image');
        }
    }

    #[Route(path: '/photos/original/{photoId}/{hash}/', requirements: ['photoId' => '\d+', 'hash' => '\S+'])]
    public function photosOriginal(ImageLocator $imageLocator, int $photoId, string $hash): BinaryFileResponse
    {
        if (!($image = $imageLocator->getImageById($photoId))) {
            throw new NotFoundHttpException('Photo not found');
        }

        if ($image->getHash() !== $hash) {
            throw new NotFoundHttpException('Invalid photo hash!');
        }

        if (!file_exists($image->getImagePath())) {
            throw new NotFoundHttpException('Photo was not found on disk: '.$image->getImagePath());
        }

        return new BinaryFileResponse($image->getImagePath());
    }
}
