<?php


namespace AutoAdmin\Bundle\Media\Mapper;


use AutoAdmin\Bundle\Media\Model\FileInterface;
use AutoAdmin\Bundle\Media\Model\ImageInterface;
use AutoAdmin\Bundle\Media\Model\MediaInterface;
use Exception;
use ReflectionClass;

class TypedFileMapper implements MapperInterface
{
    private array $mapperConfig;

    public function __construct(array $mapperConfig)
    {
        $this->mapperConfig = $mapperConfig;
    }

    public function supports(MediaInterface $media): bool
    {
        return $media instanceof ImageInterface
            || $media instanceof FileInterface;
    }

    public function getUploadPath(MediaInterface $media): string
    {
        return $this->replaceTokens($this->mapperConfig['upload_path'], $media);
    }

    public function replaceTokens(string $sourceString, MediaInterface $media): string
    {
        $replacements = [
            '{CLASS_SLUG}' => $this->guessSlug($media),
        ];

        return str_replace(array_keys($replacements), array_values($replacements), $sourceString);
    }

    protected function guessSlug(MediaInterface $media): string
    {
        $reflectionClass = new ReflectionClass($media);

        if ($reflectionClass->implementsInterface(ImageInterface::class)) {
            return 'image';
        }

        if ($reflectionClass->implementsInterface(FileInterface::class)) {
            return 'file';
        }

        throw new Exception('Could not guess class slug for "%s"', get_class($media));
    }

    public function getPublicPath(MediaInterface $media): string
    {
        return $this->replaceTokens($this->mapperConfig['public_path'], $media);
    }
}
