<?php
declare(strict_types=1);

namespace Leadlion\Autogedal\Model\Import;

use Firebear\ImportExport\Helper\MediaHelper;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem\DriverPool;

class Uploader extends \Firebear\ImportExport\Model\Import\Uploader
{
    /**
     * Correct filename with special chars and spaces; also trim excessively long filenames
     *
     * @param string $fileName
     * @return string
     * @throws \InvalidArgumentException
     */
    public static function getCorrectFileName($fileName): string
    {
        $fileName = preg_replace('/[^a-z0-9_\\-\\.]+/i', '_', $fileName);
        $fileInfo = pathinfo($fileName);
        $fileInfo['extension'] = $fileInfo['extension'] ?? '';

        // account for excessively long filenames that cannot be stored completely in database
        if (strlen($fileInfo['basename']) > 255) {
            throw new \InvalidArgumentException('Filename is too long; must be 255 characters or less');
        }

        if (preg_match('/^_+$/', $fileInfo['filename'])) {
            $fileName = 'file.' . $fileInfo['extension'];
        }

        return $fileName;
    }

    /**
     * @param $obj
     * @param $prop
     *
     * @return mixed
     * @throws \ReflectionException
     */
    private function accessProtectedPropery($obj, $prop)
    {
        $reflection = new \ReflectionClass($obj);
        $property = $reflection->getProperty($prop);
        $property->setAccessible(true);
        return $property->getValue($obj);
    }

    /**
     * @param string $mime_type
     *
     * @return string
     */
    private function getImageMimeType($mime_type = 'image/jpeg')
    {
        $fileExtension = array_flip($this->_allowedMimeTypes)[$mime_type] ?? 'jpeg';
        return '.' . $fileExtension;
    }

    /**
     * @param $fileName
     *
     * @return bool
     */
    private function isImageQueryString($fileName)
    {
        return strpos($fileName, '?') !== false;
    }
}