<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\DocStoreBundle\Serializer\Normalizer;

use Chill\DocStoreBundle\Entity\StoredObjectVersion;
use Chill\MainBundle\Serializer\Normalizer\UserNormalizer;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class StoredObjectVersionNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
    use NormalizerAwareTrait;

    final public const WITH_POINT_IN_TIMES_CONTEXT = 'with-point-in-times';

    final public const WITH_RESTORED_CONTEXT = 'with-restored';

    public function normalize($object, ?string $format = null, array $context = [])
    {
        if (!$object instanceof StoredObjectVersion) {
            throw new \InvalidArgumentException('The object must be an instance of '.StoredObjectVersion::class);
        }

        $data = [
            'id' => $object->getId(),
            'filename' => $object->getFilename(),
            'version' => $object->getVersion(),
            'iv' => array_values($object->getIv()),
            'keyInfos' => $object->getKeyInfos(),
            'type' => $object->getType(),
            'createdAt' => $this->normalizer->normalize($object->getCreatedAt(), $format, $context),
            'createdBy' => $this->normalizer->normalize($object->getCreatedBy(), $format, [...$context, UserNormalizer::AT_DATE => $object->getCreatedAt()]),
        ];

        $normalizationGroups = $context[AbstractNormalizer::GROUPS] ?? [];

        if (is_string($normalizationGroups)) {
            $normalizationGroups = [$normalizationGroups];
        }

        if (in_array(self::WITH_POINT_IN_TIMES_CONTEXT, $normalizationGroups, true)) {
            $data['point-in-times'] = $this->normalizer->normalize($object->getPointInTimes(), $format, $context);
        }

        if (in_array(self::WITH_RESTORED_CONTEXT, $normalizationGroups, true)) {
            $data['from-restored'] = $this->normalizer->normalize($object->getCreatedFrom(), $format, [AbstractNormalizer::GROUPS => ['read']]);
        }

        return $data;
    }

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