<?php


namespace AutoAdmin\Bundle\BrickBuilder\Serializer;

use AutoAdmin\Bundle\BrickBuilder\Brick\BrickAdminHelper;
use AutoAdmin\Bundle\BrickBuilder\Model\BrickInterface;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class BrickNormalizer implements NormalizerInterface
{
    private NormalizerInterface $normalizer;
    private BrickAdminHelper $adminHelper;

    public function __construct(NormalizerInterface $normalizer, BrickAdminHelper $adminHelper)
    {
        $this->normalizer = $normalizer;
        $this->adminHelper = $adminHelper;
    }

    public function normalize($brick, string $format = null, array $context = [])
    {
        $data = $this->normalizer->normalize($brick, $format, $context);

        // here, we don't want an empty collection transformed to json as "{}", force it to array
        if ($data['children'] instanceof Collection) {
            $data['children'] = $data['children']->toArray();
        }

        $data['preview'] = $this->adminHelper->getAdminPreview($brick);
        $data['isContainer'] = $this->adminHelper->isContainerBrick($brick);
        $data['nature'] = $this->adminHelper->getBrickNature($brick);
        $data['hasForm'] = $this->adminHelper->hasAdminForm($brick);
        $data['allowedChildren'] = !$data['isContainer'] ? [] : $this->adminHelper->getAllowedChildren($brick);

        return $data;
    }

    public function supportsNormalization($data, string $format = null, array $context = []): bool
    {
        return $data instanceof BrickInterface;
    }
}
