<?php

namespace Mnv\Core\Uploads;

use Mnv\Core\Config;
use Symfony\Component\HttpFoundation\File\UploadedFile as SymfonyUploadedFile;

use Intervention\Image\Image;
use Intervention\Image\ImageManager;


/**
 * Class ImageGenerator
 * @package Mnv\Core\Imagine\Action
 */
class ImageGenerator extends AbstractImagineGenerator implements ActionInterface
{

    /** @var Image */
    private Image $image;

    /** @var ImageManager  */
    private ImageManager $manager;

    public function __construct(string $realPath, string $path, int $managerId)
    {
        parent::__construct($realPath,  $path, $managerId);

        if (Config::getValue('image_library') != 2) {
            if (extension_loaded('imagick') && class_exists('Imagick'))	{
                $this->driver = 'imagick';

                if (!\Imagick::queryFormats('WEBP') && function_exists('imagewebp') && Config::getValue('image_library') != 1 ) {
                    $this->driver = 'gd';
                }
            }
        }

        $this->manager = new ImageManager(['driver' => $this->driver]);
    }

    /**
     *
     * @param SymfonyUploadedFile $file
     * @return $this
     */
    public function init(SymfonyUploadedFile $file): ImageGenerator
    {
        $this->file = $file;
        $this->generatorExtension($file->getClientOriginalExtension());

        /** название файла */
        if (Config::getValue('keep_original_image_name'))
            $this->codeImage = pregGetValue('/([^\/]+)\.[^\.]+$/', $this->file->getClientOriginalName());
        if (empty($this->codeImage))
            $this->codeImage = substr(md5(number_format(time() * rand(),0,'','')),3,12);

        /** достаем временный файл для обработки */
        $this->image = $this->manager->make($this->file->getPathname());

        return $this;
    }

    /**
     * @return bool|int|string|null
     */
    public function save()
    {
        $images = [
            'name'      => $this->codeImage . '.' . $this->extension,
            'size'      => $this->file->getSize() ?? null,
            'mimeType'  => $this->file->getClientMimeType(),
        ];

        $this->resizeImage($this->image->getWidth(), $this->image->getHeight(),$this->realPath . $this->codeImage . '.' . $this->extension);
        foreach ($this->sizes as $size) {
            $sizes = $this->autoSize(Config::getValue($size . '_thumb'));
            $this->resizeImage($sizes[0], $sizes[1], $this->realPath  . $size . '/' . $this->codeImage . '.' . $this->extension);
        }

        return $this->saveFile($images);
    }

    /**
     * обработка и сохранение размеров
     *
     * @param int $width
     * @param int $height
     * @param string $path
     */
    public function resizeImage(int $width, int $height, string $path)
    {
        if (Config::getValue('allow_watermark') && $this->extension != 'gif') {
            $this->generateWatermark();
        }

        $this->image->resize($width, $height, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        })->save($path, Config::getValue('thumbnail_quality'), $this->extension);

    }



    private function generateWatermark()
    {
        $fontOptions = [
            'size'      => Config::getValue('watermark_font'),
            'color'     => [
                'light' => Config::getValue('watermark_color_light'),
                'dark'  => Config::getValue('watermark_color_dark')
            ],
            'alpha'     => intval(Config::getValue('watermark_opacity')),
            'angle'     => Config::getValue('watermark_rotate'),
            'margin'    => 20,
        ];
            $this->image->text(Config::getValue('watermark_text'), $this->image->width() / 2, $this->image->height() / 2, function ($font) use ($fontOptions) {
                $font->file($this->fontWatermark);
                $font->size($fontOptions['size']);
                $font->color($fontOptions['color']['light']);
                $font->align('center');
                $font->valign('top');
                $font->angle($fontOptions['angle']);

            });
//        for($i = 15, $j = 25; $i < $this->image->width() && $j < $this->image->height(); $i += 40, $j += 40) {
//            $this->image->text(Config::getValue('watermark_text'), $i, $j, function ($font) use ($fontOptions) {
//                $font->file($this->fontWatermark);
//                $font->size($fontOptions['size']);
//                $font->color($fontOptions['color']['light']);
//                $font->align('center');
//                $font->valign('top');
//                $font->angle($fontOptions['angle']);
//
//            });
//        }

//        $text_distanceyposition = 100;
//        $text_distancexposition = 220;
//
//        $x = 0;
//
//        while ($x < $this->image->width()) {
//            $y = 0;
//
//            while($y < $this->image->height()) {
//                $this->image->text(Config::getValue('watermark_text'),  $x, $y, function ($font) use ($fontOptions) {
//                    $font->file($this->fontWatermark);
//                    $font->size($fontOptions['size']);
//                    $font->color($fontOptions['color']['light']);
//                    $font->align('center');
//                    $font->valign('top');
//                    $font->angle($fontOptions['angle']);
//
//                });
//                $y += $text_distanceyposition;
//            }
//
//            $x += $text_distancexposition;
//        }
    }


}