<?php

namespace AutoAdmin\Bundle\Content\Breadcrumbs;

use AutoAdmin\Bundle\Content\Entity\AbstractContentTranslation;
use AutoAdmin\Bundle\Content\Model\NameInterface;
use AutoAdmin\Bundle\Content\Model\TitleInterface;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Model\UntranslatableInterface;
use AutoAdmin\Bundle\Content\Routing\ContentRouter;
use Doctrine\Common\Collections\ArrayCollection;

class BreadcrumbsService
{
    public function __construct(
        private readonly ContentRouter $contentRouter,
        private readonly ArrayCollection $path = new ArrayCollection()
    ) {
    }

    public function add(string $label, string $url = null, array $extra = []): void
    {
        $this->path->add(
            [
                'label' => $label,
                'url' => $url,
                'extra' => $extra,
            ]
        );
    }

    public function addContent(object $content, $onlyText = true): void
    {
        if ($content instanceof TranslatableInterface) {
            /** @var AbstractContentTranslation $tr */
            $tr = $content->getCurrentTranslation();
            $this->add(
                $tr->getName(),
                $onlyText !== true ? $this->contentRouter->generate($content) : null
            );
        } elseif ($content instanceof UntranslatableInterface && $content instanceof TitleInterface) {
            $this->add(
                $content->getTitle(),
                $onlyText !== true ? $this->contentRouter->generate($content) : null
            );
        } elseif ($content instanceof UntranslatableInterface && $content instanceof NameInterface) {
            $this->add(
                $content->getName(),
                $onlyText !== true ? $this->contentRouter->generate($content) : null
            );
        } else {
            throw new \Exception(sprintf('Could not generate breadcrumb item for "%s".', $content::class));
        }
    }

    public function compile()
    {
        return $this->path->toArray();
    }

    public function reset(): void
    {
        $this->path->clear();
    }
}
