<?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($object, string $format = null, array $context = []): array
    {
        $data = $this->normalizer->normalize($object, $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($object);
        $data['isContainer'] = $this->adminHelper->isContainerBrick($object);
        $data['nature'] = $this->adminHelper->getBrickNature($object);
        $data['hasForm'] = $this->adminHelper->hasAdminForm($object);
        $data['allowedChildren'] = !$data['isContainer'] ? [] : $this->adminHelper->getAllowedChildren($object);

        return $data;
    }

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

    public function getSupportedTypes(?string $format): array
    {
        return [
            BrickInterface::class => true,
        ];
    }
}
