<?php


namespace Mnv\Core\Uploads;

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

/**
 * Class AbstractImagineGenerator
 * @package Mnv\Core\Uploads
 */
abstract class AbstractImagineGenerator
{

    /** @var array|string[]  */
    protected array $sizes = array('large', 'medium', 'small');

    /** @var  Filesystem */
    public Filesystem $filesystem;

    /** @var string  */
    public string $realPath;

    /** @var string */
    public string $path;

    /** @var int */
    public int $managerId;

    /** @var SymfonyUploadedFile */
    protected SymfonyUploadedFile $file;

    /** @var false|string $codeImage */
    protected $codeImage;

    /** @var string  */
    protected string $driver = 'gd';

    /** @var string  */
    protected string $extension;

    /** @var string  */
    protected string $fontWatermark = GLOBAL_ROOT . '/admin/assets/fonts/verdana.ttf';

    /**
     * AbstractImagineGenerator constructor.
     * @param string $realPath
     * @param string $path
     * @param int $managerId
     */
    public function __construct(string $realPath, string $path, int $managerId)
    {

        $this->filesystem  = new Filesystem();
        $this->realPath     = $realPath;
        $this->path         = $path;
        $this->managerId    = $managerId;

    }

    abstract public function init(SymfonyUploadedFile $file);

    /**
     * если включена конвертация файла в `webp` то нам нужно знать,
     * если это `gif` то нельзя конвертировать в `webp`,
     * для остальных расширений разрешена конвертация в `webp`
     */
    protected function generatorExtension($originalExtension)
    {
        if ($originalExtension == 'gif') {
            $this->extension = $originalExtension;
        } else {
            $this->extension = (Config::getValue('force_webp') == 1) ? "webp" : $originalExtension;
        }
    }


    /**
     * @param $file
     * @return bool|int|string|null
     */
    public function saveFile($file)
    {
        if ($file) {
            $insertFiles = array_filter([
                'directory' => $this->filesystem->basename($this->realPath),
                'path'      => '/uploads/' . $this->path,
                'fileName'  => $file['name'],
                'size'      => $file['size'],
                'mime_type' => $file['mimeType'] ?? null,
                'addedBy'   => !empty($this->managerId) ? $this->managerId : 0,
                'addedOn'   => gmdate('Y-m-d H:i:s'),
            ]);

            if (!empty($insertFiles)) {
                if ($fileId = connect('files')->insert($insertFiles)) return $fileId;
            }
        }

        return false;
    }

    /**
     * Формируем размеры для обработки файла
     * @param $size
     * @return array|false|string[]
     */
    protected function autoSize($size)
    {
        $sizes = [];
        if (strpos($size, 'x') !== false) {

            $sizes = explode("x", $size);

            if (count($sizes) == 2) {
                $sizes[0] = intval($sizes[0]);
                $sizes[1] = intval($sizes[1]);

            } else {
                $sizes[0] = intval($sizes[0]);
                $sizes[1] = intval($sizes[0]);
            }

        } else {
            $sizes[0] = intval($size);
            $sizes[1] = intval($size);
        }

        return $sizes;
    }

}