<?php

namespace Eae\Support;

use Image;
use Config;
use Eae\Exception\InvalidConfigurationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ImageGenerator
{
    private $allowedSizes;

    public function __construct()
    {
        $this->allowedSizes = Config::get("image_resize");
    }

    public function transform($originalFilePath, $targetFilePath, $transformationSize)
    {

        if (!isset($this->allowedSizes[$transformationSize])) {
            throw new InvalidConfigurationException("Invalid size");
        }

        if (!file_exists($originalFilePath)) {
            throw new NotFoundHttpException();
        }

        $size = $this->allowedSizes[$transformationSize];


        $quality = 90;
        if (isset($size["quality"])) {
            $quality = $size["quality"];
        }

        $img = Image::make($originalFilePath);
        $width = !empty($size["width"]) ? $size["width"] : null;
        $height = !empty($size["height"]) ? $size["height"] : null;

        if (!is_null($width) && !is_null($height)) {
            $img->fit($width, $height);
        } else {
            $img->resize($width, $height, function ($constraint) {
                $constraint->aspectRatio();
            });
        }
        $img->save($targetFilePath, $quality);
        return $img;
    }

}