<?php

namespace AutoAdmin\Bundle\Media\Library;


class MediaTypeResolver
{
    protected array $mapping;

    protected array $slugToClass;
    protected array $classToSlug;

    public function __construct(array $mediaConfig)
    {
        $mappings = $mediaConfig['media_mappings'] ?? [];

        $this->mapping = $mappings;

        $this->slugToClass = array_combine(
            array_column($this->mapping, 'type'),
            array_column($this->mapping, 'class'),
        );
        $this->classToSlug = array_combine(
            array_column($this->mapping, 'class'),
            array_column($this->mapping, 'type'),
        );
    }

    public function getAllSlugs(): array
    {
        return array_values($this->classToSlug);
    }

    public function getAllClasses(): array
    {
        return array_values($this->slugToClass);
    }

    public function getTypeSlug(string $class): string
    {
        return $this->classToSlug[$class]
            ?? throw new \RuntimeException('Unknown media type class: '.$class);
    }

    public function getTypeClass(string $typeSlug): string
    {
        return $this->slugToClass[$typeSlug]
            ?? throw new \RuntimeException('Unknown media type slug: '.$typeSlug);
    }

    public function getTypeConfig(string $typeSlug): array
    {
        // if class, get slug
        if (stripos($typeSlug, '\\')) {
            $typeSlug = $this->getTypeSlug($typeSlug);
        }

        return $this->mapping[$typeSlug]
            ?? throw new \RuntimeException('No media type config slug: '.$typeSlug);

    }

    public function getSerializableConfig(array $typesSlugs)
    {
        $allowedKeys = [
            'type',
            'mime_types',
            'label',
            'display_max_size',
        ];

        $filteredMapping = [];
        foreach ($this->mapping as $slug => $item) {
            if (in_array($slug, $typesSlugs)) {
                $filteredMapping[$slug] = array_intersect_key($this->mapping[$slug], array_flip($allowedKeys));
            }
        }

        return $filteredMapping;
    }
}
