<?php

    use Eae\Exception\InvalidConfigurationException;
    use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    use Eae\Support\ImageGenerator;

    class ImageThumbController extends Controller
    {

        public function getThumb($filename)
        {
            $filename = strip_tags($filename);
            $fileInfo = pathinfo($filename);
            $thumbFileName = $fileInfo["basename"];
            $extension = $fileInfo["extension"];
            $pos = strrpos($filename, "_");
            if ($pos === FALSE) {
                throw new InvalidConfigurationException("Invalid size");
            }
            $originalFileName = substr($fileInfo["filename"], 0, $pos) . ".{$extension}";
            $originalImagePath = Config::get("path.internal.media") . "/{$originalFileName}";
            $targetFilePath = Config::get("path.internal.thumbs") . "/{$filename}";
            if (!file_exists($originalImagePath)) {
                App::abort(404);
            }
            $transformationSize = substr($fileInfo["filename"], $pos + 1);

            try {
                $img = new ImageGenerator();
                $newImg = $img->transform($originalImagePath, $targetFilePath, $transformationSize);

                return $newImg->response();
            } catch (NotFoundHttpException $e) {
                throw $e;
            } catch (Throwable $e) {
                App::abort(500, $e);
            }
        }

    }
