<?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\MainBundle\Serializer\Normalizer;

use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberUtil;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

class PhonenumberNormalizer implements ContextAwareNormalizerInterface, DenormalizerInterface
{
    private readonly string $defaultCarrierCode;

    private readonly PhoneNumberUtil $phoneNumberUtil;

    public function __construct(ParameterBagInterface $parameterBag)
    {
        $this->defaultCarrierCode = $parameterBag->get('chill_main')['phone_helper']['default_carrier_code'];
        $this->phoneNumberUtil = PhoneNumberUtil::getInstance();
    }

    /**
     * @param string|null $data
     * @param mixed|null  $format
     *
     * @throws UnexpectedValueException
     */
    public function denormalize($data, $type, $format = null, array $context = [])
    {
        if ('' === trim((string) $data)) {
            return null;
        }

        try {
            return $this->phoneNumberUtil->parse($data, $this->defaultCarrierCode);
        } catch (NumberParseException) {
            $phonenumber = new PhoneNumber();
            $phonenumber->setRawInput($data);

            return $phonenumber;
        }
    }

    public function normalize($object, ?string $format = null, array $context = []): string
    {
        if ('docgen' === $format && null === $object) {
            return '';
        }

        return $this->phoneNumberUtil->formatOutOfCountryCallingNumber($object, $this->defaultCarrierCode);
    }

    public function supportsDenormalization($data, $type, $format = null)
    {
        return 'libphonenumber\PhoneNumber' === $type;
    }

    public function supportsNormalization($data, ?string $format = null, array $context = []): bool
    {
        if ($data instanceof PhoneNumber && 'json' === $format) {
            return true;
        }

        if ('docgen' === $format && (
            $data instanceof PhoneNumber || PhoneNumber::class === ($context['docgen:expects'] ?? null)
        )) {
            return true;
        }

        return false;
    }
}
