<?php

namespace App\Libs\Services;

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

class MediaService
{
    public function generateMediaThumb($filename)
    {
        $fileInfo = pathinfo($filename);
        $extension = $fileInfo["extension"];
        $isWebp = false;

        if ($extension == 'webp') {
            $fileparts = explode('.', $fileInfo["filename"]);
            $extension = !empty($fileparts[1]) ? $fileparts[1] : $extension;
            $ofilename = $fileparts[0];
            $filename = !empty($fileparts[1]) ? $fileparts[0] . '.' . $extension : $filename;
            $isWebp = true;
        } else {
            $ofilename = $fileInfo["filename"];
        }
        $pos = strrpos($ofilename, "_");
        if ($pos === false) {
            throw new InvalidConfigurationException("Invalid size");
        }
        $originalFileName = substr($ofilename, 0, $pos).".{$extension}";

        $originalFilePath = config("path.internal.media")."/{$originalFileName}";
        $targetFilePath = config("path.internal.thumbs")."/{$filename}";
        $transformationSize = substr($ofilename, $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 = 80;

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

        //TODO S3
        $img = Image::read(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");
        }

        switch($size['type']) {
            case 'resize':
                $img->scale($size["width"], $size["height"])->resizeCanvas($size["width"], $size["height"]);
                break;
            case 'resize_noup':
                $img->scaleDown(width: $size["width"]);
                break;
            case 'fit':
                $img->cover($width, $height);
                break;
        }

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

        $img->save(Storage::path($targetFilePath), $quality);
        unset($img);
        if ($isWebp) {
            exec("cwebp -q 80 " . Storage::path($targetFilePath) . " -o " . Storage::path($targetFilePath . '.webp') . " ");
            return Storage::path($targetFilePath . '.webp');
        }

        return Storage::path($targetFilePath);
    }
}
