<?php

namespace AutoAdmin\Bundle\Content\Service;

use AutoAdmin\Bundle\Content\Entity\Interfaces\DuplicatorInterface;
use Doctrine\Common\Util\ClassUtils;
use LogicException;

class DuplicatorService
{
    /**
     * @var DuplicatorInterface[]|array
     */
    protected array $duplicators = [];

    public function duplicate($entity, $parent = null)
    {
        if ($entity == null) {
            return null;
        }

        $class = ClassUtils::getRealClass(get_class($entity));
        $duplicate = new $class();

        foreach ($this->duplicators as $duplicator) {
            if (!$duplicator->isSupported($entity)) {
                continue;
            }

            $duplicate = $duplicator->duplicate($entity, $duplicate, $parent);
        }

        return $duplicate;
    }

    public function addDuplicator($definition)
    {
        $class = get_class($definition);

        if (isset($this->duplicators[$class])) {
            throw new LogicException(
                sprintf(
                    'Duplicator "%s" already exists',
                    $class
                )
            );
        }

        $this->duplicators[$class] = $definition;
    }
}
