<?php

namespace Mnv\Core\Uploads;

use getID3;
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 ?? [];

        if (!empty($file)) {

            $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'];
                    }
                }
            }

            if (isset($file['mime_type']) && $file['mime_type'] == 'audio/mpeg') {
                $getID3 = new getID3;
                $ThisFileInfo = $getID3->analyze(GLOBAL_ROOT.$file['path'].$file['fileName']);
                $imageSizes['playtime_string'] = $ThisFileInfo['playtime_string'];
            }
        }


        return $imageSizes;
    }


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