<?php

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

class ImageThumbController extends Controller{

    public function getThumb($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}";
        $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);
        }
    }

}
