<?php


namespace AutoAdmin\Bundle\Seo\Schema\Model;


use Spatie\SchemaOrg\BaseType;
use Spatie\SchemaOrg\BreadcrumbList;
use Spatie\SchemaOrg\Graph;
use function count;

/**
 * Hold an indexed list of BaseType schemas
 * Indexes can be tested in order to keep only one representation for a given fqcn, for example {@see BreadcrumbList}
 */
class SchemaStack
{
    /**
     * @var array<BaseType>
     */
    protected array $representations = [];

    /**
     * Used to add {@see BaseType} schema representations.
     * Shortcut for {@see self::addRepresentation}
     *
     * @param BaseType $schema
     * @return $this
     */
    public function add(BaseType $schema): self
    {
        return $this->addRepresentation($schema);
    }

    /**
     * Shortcut for {@see self::hasType}
     *
     * @param string $schemaFqcn
     * @return bool
     */
    public function has(BaseType $schema): bool
    {
        return  $this->hasType(get_class($schema));
    }


    public function getRepresentations(): array
    {
        return $this->representations;
    }

    public function setRepresentations(array $representations): void
    {
        $this->representations = $representations;
    }

    public function hasRepresentations(): bool
    {
        return count($this->representations) > 0;
    }

    public function addRepresentation(BaseType $schema): self
    {
        $type = get_class($schema);
        $this->representations[$type] = $schema;

        return $this;
    }

    public function hasType(string $type): bool
    {
        return isset($this->representations[$type]);
    }

    public function getType(string $type): ?BaseType
    {
        return $this->representations[$type] ?: null;
    }

    public function toScript(): string
    {
        $graph = new Graph();

        /** @var BaseType $representation */
        foreach ($this->representations as $representation) {
            $graph->add($representation);
        }

        return $graph->toScript();
    }
}
