<?php

namespace KupShop\DevelopmentBundle\Controller;

use KupShop\KupShopBundle\Config;
use KupShop\KupShopBundle\Util\System\PathFinder;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
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}"})
     */
    public function thumbnailAction(Request $request, $image_id, $type, $lang = null, $version = null)
    {
        if (Config::get()['get_remote_images'] ?? false) {
            $imageClass = new \Image();

            try {
                $this->downloadRemoteImage($image_id, $type, $lang, $version);
                $image = $imageClass->getImage($image_id, $type, $lang, $version);
                $image = $imageClass->createThumbnail($image);
                $imageClass->outputImage($image);
            } catch (\UnexpectedValueException $e) {
                // Pass to redirect
            }
        }

        try {
            $request->attributes->replace([
                '_controller' => 'KupShop\CatalogBundle\Controller\ImageController::thumbnailAction',
                'image_id' => $image_id,
                'type' => $type,
                'lang' => $lang,
                'version' => $version,
            ]);

            return $this->container->get('http_kernel')->handle($request, HttpKernelInterface::SUB_REQUEST, catch: false);
        } catch (NotFoundHttpException) {
            $address = Config::get()->getFromArray('Addr');
            $url = $address['full_original'].ltrim($request->getRequestUri(), '/');

            $response = new RedirectResponse($url, 302);
            $response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
            $response->setMaxAge(3600);

            return $response;
        }
    }

    private function downloadRemoteImage($image_id, $type, $lang, $version)
    {
        $cfg = Config::get();
        $pathFinder = PathFinder::getService();

        $imageClass = new \Image();
        if ($image = $imageClass->getImage($image_id, $type, $lang, $version)) {
            // soubor uz existuje
            if (file_exists($pathFinder->getShopDir().$image['original'])) {
                return true;
            }

            $address = $cfg->getFromArray('Addr');

            $dir = explode('/', $image['original']);
            array_pop($dir);
            $dir = $pathFinder->getShopDir().join('/', $dir);
            if (!file_exists($dir)) {
                mkdir($dir, 0777, true);
            }

            $url = $address['full_original'].ltrim($image['original'], '/');

            $downloader = new \Downloader();
            if ($downloader->copyRemoteFile($url, $pathFinder->getShopDir().$image['original'])) {
                return true;
            }
        }

        return false;
    }

    /**
     * @Route("/data/{path}", requirements={"path"=".+"})
     */
    public function dataToUpstreamAction(Request $request, $path)
    {
        $address = Config::get()->getFromArray('Addr');
        $url = $address['full_original'].'data/'.ltrim($path, '/');

        return new RedirectResponse($url);
    }
}
