<?php

namespace App\Libs\Services;

use App\Libs\Exception\InvalidConfigurationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class MediaService {

    /**
     * Generates the thumb image and return the image object
     *
     * @param  string  $filename
     *
     * @return Intervention\Image\Image
     * @throws InvalidConfigurationException
     */
    public function generateMediaThumb($filename)
    {
        $fileInfo = pathinfo($filename);
        $extension = $fileInfo["extension"];
        $pos = strrpos($filename, "_");
        if ($pos === false) {
            throw new InvalidConfigurationException("Invalid size");
        }

        $originalFileName = substr($fileInfo["filename"], 0, $pos).".{$extension}";
        $originalFilePath = config("path.internal.media")."/{$originalFileName}";
        $targetFilePath = config("path.internal.thumbs")."/{$filename}";
        $transformationSize = substr($fileInfo["filename"], $pos + 1);

        $allowedSizes = config('image_resize');
        if (!isset($allowedSizes[$transformationSize])) {
            throw new InvalidConfigurationException("Invalid size");
        }

        if (!Storage::has($originalFilePath)) {
            throw new NotFoundHttpException();
        }

        $size = $allowedSizes[$transformationSize];
        $quality = 90;

        if (isset($size["quality"])) {
            $quality = $size["quality"];
        }

        //TODO S3
        $img = Image::make(Storage::path($originalFilePath));
        $width = !empty($size["width"]) ? $size["width"] : null;
        $height = !empty($size["height"]) ? $size["height"] : null;

        if (is_null($width) && is_null($height)) {
            throw new InvalidConfigurationException("The size {$transformationSize} must have at least a width or a height");
        }

        if (!is_null($width) && !is_null($height)) {
            $img->fit($width, $height);
        } else {
            $img->resize($width, $height, function ($constraint) {
                $constraint->aspectRatio();
            });
        }

        if (!Storage::has(config('path.internal.thumbs'))) {
            Storage::makeDirectory(config('path.internal.thumbs'));
        }

        //TODO S3
        $img->save(Storage::path($targetFilePath), $quality);
        return $img;
    }
}
