<?php
namespace App\Helper;
use App\Entity\File;
use Intervention\Image\ImageManager;

class ImagePreparation {

    public function prepare(File $file, ?int $size, ?File $watermarkFile) :string {
        $img = $this->prepareImage($file, $size, $watermarkFile);
        $jpg = (string)$img->encode('jpg', 100);
        $img->destroy();
        return $jpg;
    }
    public function prepareImage(File $file, ?int $size, ?File $watermarkFile) : \Intervention\Image\Image {
        $manager = new ImageManager(array('driver' => 'imagick'));
        $img = $manager->make($file->getContent());
        $watermark = null;
        if(!is_null($watermarkFile)) {
            $watermark = $manager->make($watermarkFile->getContent());
        }

        if(!is_null($size)) {
            $img = $this->resizeImage($img, $size);
        }
        if(!is_null($watermark)) {
            $img = $this->addWatermarkImage($img, $watermark);
        }

        return $img;

    }

    private function resizeImage(\Intervention\Image\Image $img, int $size) : \Intervention\Image\Image
    {
        if($img->getWidth() > $img->getHeight()) {
            $newWidth = $size;
            $newHeight = $img->getHeight() * ($newWidth / $img->getWidth() );
        } else {
            $newHeight = $size;
            $newWidth = $img->getWidth() * ($newHeight / $img->getHeight());
        }
        $img->resize($newWidth, $newHeight);

        return $img;
    }

    private function addWatermarkImage(\Intervention\Image\Image $img, \Intervention\Image\Image $watermark) : \Intervention\Image\Image {
        if($watermark->getWidth() > $img->getWidth()) {
            $newWidth = $img->getWidth() / 1.2;
            $newHeight = $watermark->getHeight() * ($newWidth / $watermark->getWidth());
            $watermark->resize($newWidth, $newHeight);
        }
        if($watermark->getHeight() > $img->getHeight()) {
            $newHeight = $img->getHeight() / 1.1;
            $newWidth = $watermark->getWidth() * ($newHeight / $watermark->getHeight());
            $watermark->resize($newWidth, $newHeight);
        }
        $watermark->opacity(40);
        $img->insert($watermark, 'center');
        $watermark->destroy();
        return $img;
    }

    private function addWatermarkText(\Intervention\Image\Image $img, string $text) : \Intervention\Image\Image {
        $img->resizeCanvas(0, 28, 'top', true, "#000000");
        $img->text($text, $img->getWidth() - 10, $img->getHeight() - 25, function($font) {
            $font->file(storage_path("OpenSans-Light.ttf"));
            $font->size(18);
            $font->color('#ffffff');
            $font->align('right');
            $font->valign('top');
        });
        return $img;
    }
}
