<?php

namespace AutoAdmin\Bundle\Content\Duplicator;

use AutoAdmin\Bundle\BrickBuilder\Attributes\BrickBuilder;
use AutoAdmin\Bundle\Content\Model\BrickInterface;

class BrickDuplicator extends AbstractDuplicator
{
    /**
     * @return string[]
     */
    public function supportInterfaces(): array
    {
        return [
            BrickInterface::class,
        ];
    }

    /**
     * @param BrickInterface $entity
     * @param BrickInterface $duplicate
     *
     * @return BrickInterface
     */
    public function duplicate(object $entity, object $duplicate, ?object $parent = null): object
    {
        $brickBuilderProps = $this->getPropertiesWithAttribute($entity, BrickBuilder::class);
        /** @var \ReflectionProperty $brickBuilderProp */
        foreach ($brickBuilderProps as $brickBuilderProp) {
            $brick = $brickBuilderProp->getValue($entity);
            if ($brick !== null) {
                $newBrick = $this->builderService->replicate($brick);
                $brickBuilderProp->setValue($duplicate, $newBrick);
            }
        }

        return $duplicate;
    }

    public function isSupported($entity): bool
    {
        $isInterfaceSupported = parent::isSupported($entity);
        $brickBuilderProps = $this->getPropertiesWithAttribute($entity, BrickBuilder::class);

        return $isInterfaceSupported || !empty($brickBuilderProps);
    }
}
