<?php

namespace AutoAdmin\Bundle\Media\Library;

use AutoAdmin\Bundle\Media\Attributes\LinkedMedia;
use AutoAdmin\Bundle\Media\Model\Library\LinkedMediaPropConfig;

class LinkedMediaPropHelper
{
    public function __construct(
        protected MediaTypeResolver $mediaTypeResolver
    ) {
    }

    public function getLinkedPropsFromObject(object $obj)
    {
        return $this->getLinkedProps(get_class($obj));
    }

    /**
     * @return array<LinkedMediaPropConfig>
     */
    public function getLinkedProps(string $class): array
    {
        $props = [];

        $reflectionClass = new \ReflectionClass($class);

        foreach ($reflectionClass->getProperties() as $prop) {
            if ($prop) {
                $attributes = $prop->getAttributes(LinkedMedia::class);
                if ($attrib = $attributes[0] ?? null) {
                    $mappings = $attrib->getArguments()['mappings'] ?? $this->mediaTypeResolver->getAllSlugs();
                    $props[] = new LinkedMediaPropConfig($prop, [
                        'mappings' => $mappings,
                    ]);
                }
            }
        }


        return $props;
    }

    public function getLinkedProp(string $class, string $propName): ?LinkedMediaPropConfig
    {
        $propConfigs = $this->getLinkedProps($class);

        foreach ($propConfigs as $propConfig) {
            if ($propConfig->getProp()->getName() === $propName) {
                return $propConfig;
            }
        }

        return null;
    }
}