<?php

namespace Mnv\Core\Uploads;

use Mnv\Core\Singleton\SingletonTrait;

/**
 * Class ImageSizes
 * @package Mnv\Core\Files\Image
 */
final class ImageSizes
{

    use SingletonTrait;

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

    /**
     * @param $image
     * @param $file
     * @return array
     */
    public static function get($image, $file): array
    {
        $imageSizes             = $image ?? [];
        $imageSizes['fileFormat'] = self::fileExtension($file['fileName']);
        $imageSizes['fileName']   = $file['fileName'];

        if (file_exists(GLOBAL_ROOT . $file['path'] . $file['fileName'])) {
            $imageSizes['original'] = $file['path'] . $file['fileName'];
        }
        /** получим все размеры */
        foreach (self::$sizes as $size) {
            if (file_exists(GLOBAL_ROOT . $file['path'] . $size . '/' . $file['fileName'])) {
                $imageSizes[$size] = $file['path'] . $size . '/' . $file['fileName'];
            }
        }

        /** если это `svg` получим все размеры из оригинальной */
        if ($imageSizes['fileFormat'] == 'svg') {
            foreach (self::$sizes as $size) {
                if (file_exists(GLOBAL_ROOT . $file['path'] . $file['fileName'])) {
                    $imageSizes[$size] = $file['path'] . $file['fileName'];
                }
            }
        }

        return $imageSizes;
    }


    /**
     * получить расширение файла
     *
     * @param $name
     * @return false|string
     */
    public static function fileExtension($name)
    {
        $n = strrpos($name, '.');
        return ($n === false) ? '' : substr($name, $n+1);
    }
}