<?php

namespace AutoAdmin\Bundle\BrickBuilder\Builder;

use AutoAdmin\Bundle\BrickBuilder\Brick\BrickHandlerManagerInterface;
use AutoAdmin\Bundle\BrickBuilder\Entity\Brick;
use AutoAdmin\Bundle\BrickBuilder\Model\BrickInterface;
use AutoAdmin\Bundle\Content\Duplicator\Manager\DuplicatorManager;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;

class BuilderService
{
    public function __construct(
        protected FormFactoryInterface $factory,
        protected DuplicatorManager $duplicatorManager,
        protected EntityManagerInterface $em,
        protected BrickHandlerManagerInterface $handlerManager,
        protected PropertyAccessorInterface $accessor,
    ) {
    }

    public function createRoot(): BrickInterface
    {
        return (new Brick())->setType('brick.root');
    }

    public function getRoot(object $entity, string $property, bool $create = false)
    {
        $root = $this->accessor->getValue($entity, $property);
        if ($root === null && $create === true) {
            $root = $this->createRoot();
        }

        return $root;
    }

    public function buildForm($subject = null): FormBuilderInterface
    {
        $fb = $this->factory->createBuilder(FormType::class, $subject, ['data_class' => Brick::class,]);
        $fb->add('type', ChoiceType::class);
        $fb->add('id', HiddenType::class);

        return $fb;
    }

    public function reorder(BrickInterface $brick, int $position): BrickInterface
    {
        $parentBrick = $brick->getParent();
        $children = $parentBrick->getChildren();
        if ($children->contains($brick)) {
            $children->remove($children->indexOf($brick));
        }
        $childrenArray = $children->toArray();
        array_splice($childrenArray, $position, 0, [$brick]);
        $children = new ArrayCollection($childrenArray);

        $i = -1;
        /** @var BrickInterface $child */
        foreach ($children as $child) {
            $child->setPosition(++$i);
        }

        $parentBrick->setChildren($children);

        return $brick;
    }
}
