<?php

declare(strict_types=1);

namespace Drupal\Tests\serialization\Unit\Normalizer;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\TypedData\Plugin\DataType\DateTimeIso8601;
use Drupal\Core\TypedData\Plugin\DataType\IntegerData;
use Drupal\Core\TypedData\Type\DateTimeInterface;
use Drupal\serialization\Normalizer\DateTimeNormalizer;
use Drupal\Tests\serialization\Traits\JsonSchemaTestTrait;
use Drupal\Tests\UnitTestCase;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;

/**
 * Unit test coverage for @DataTypes implementing DateTimeInterface.
 *
 * @see \Drupal\Core\TypedData\Type\DateTimeInterface
 */
#[CoversClass(DateTimeNormalizer::class)]
#[Group('serialization')]
class DateTimeNormalizerTest extends UnitTestCase {

  use JsonSchemaTestTrait;

  /**
   * The tested data type's normalizer.
   *
   * @var \Drupal\serialization\Normalizer\DateTimeNormalizer
   */
  protected $normalizer;

  /**
   * The tested data type.
   *
   * @var \Drupal\Core\TypedData\Type\DateTimeInterface
   */
  protected $data;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();

    $system_date_config = $this->prophesize(ImmutableConfig::class);
    $system_date_config->get('timezone.default')
      ->willReturn('Australia/Sydney');
    $config_factory = $this->prophesize(ConfigFactoryInterface::class);
    $config_factory->get('system.date')
      ->willReturn($system_date_config->reveal());

    $this->normalizer = new DateTimeNormalizer($config_factory->reveal());
    $this->data = $this->prophesize(DateTimeInterface::class);
  }

  /**
   * Tests supports normalization.
   */
  public function testSupportsNormalization(): void {
    $this->assertTrue($this->normalizer->supportsNormalization($this->data->reveal()));

    $datetimeiso8601 = $this->prophesize(DateTimeIso8601::class);
    $this->assertTrue($this->normalizer->supportsNormalization($datetimeiso8601->reveal()));

    $integer = $this->prophesize(IntegerData::class);
    $this->assertFalse($this->normalizer->supportsNormalization($integer->reveal()));
  }

  /**
   * Tests supports denormalization.
   */
  public function testSupportsDenormalization(): void {
    $this->assertTrue($this->normalizer->supportsDenormalization($this->data->reveal(), DateTimeInterface::class));
  }

  /**
   * Tests normalize.
   */
  public function testNormalize(): void {
    $random_rfc_3339_string = $this->randomMachineName();

    $drupal_date_time = $this->prophesize(DateTimeNormalizerTestDrupalDateTime::class);
    $drupal_date_time->setTimezone(new \DateTimeZone('Australia/Sydney'))
      ->willReturn($drupal_date_time->reveal());
    $drupal_date_time->format(\DateTime::RFC3339)
      ->willReturn($random_rfc_3339_string);

    $this->data->getDateTime()
      ->willReturn($drupal_date_time->reveal());

    $normalized = $this->normalizer->normalize($this->data->reveal());
    $this->assertSame($random_rfc_3339_string, $normalized);
  }

  /**
   * Tests normalize when null.
   */
  public function testNormalizeWhenNull(): void {
    $this->data->getDateTime()
      ->willReturn(NULL);

    $normalized = $this->normalizer->normalize($this->data->reveal());
    $this->assertNull($normalized);
  }

  /**
   * Tests the denormalize function with good data.
   */
  #[DataProvider('providerTestDenormalizeValidFormats')]
  public function testDenormalizeValidFormats($normalized, $expected): void {
    $denormalized = $this->normalizer->denormalize($normalized, DateTimeInterface::class, NULL, []);
    $this->assertSame(0, $denormalized->getTimestamp() - $expected->getTimestamp());
    $this->assertEquals($expected, $denormalized);
  }

  /**
   * Data provider for testDenormalizeValidFormats.
   *
   * @return array
   *   An array of test data.
   */
  public static function providerTestDenormalizeValidFormats() {
    $data = [];

    $data['RFC3339'] = ['2016-11-06T09:02:00+00:00', new \DateTimeImmutable('2016-11-06T09:02:00+00:00')];
    $data['RFC3339 +0100'] = ['2016-11-06T09:02:00+01:00', new \DateTimeImmutable('2016-11-06T09:02:00+01:00')];
    $data['RFC3339 -0600'] = ['2016-11-06T09:02:00-06:00', new \DateTimeImmutable('2016-11-06T09:02:00-06:00')];

    $data['ISO8601'] = ['2016-11-06T09:02:00+0000', new \DateTimeImmutable('2016-11-06T09:02:00+00:00')];
    $data['ISO8601 +0100'] = ['2016-11-06T09:02:00+0100', new \DateTimeImmutable('2016-11-06T09:02:00+01:00')];
    $data['ISO8601 -0600'] = ['2016-11-06T09:02:00-0600', new \DateTimeImmutable('2016-11-06T09:02:00-06:00')];

    return $data;
  }

  /**
   * Tests the denormalize function with a user supplied format.
   */
  #[DataProvider('providerTestDenormalizeUserFormats')]
  public function testDenormalizeUserFormats($normalized, $format, $expected): void {
    $denormalized = $this->normalizer->denormalize($normalized, DateTimeInterface::class, NULL, ['datetime_allowed_formats' => [$format]]);
    $this->assertSame(0, $denormalized->getTimestamp() - $expected->getTimestamp());
    $this->assertEquals($expected, $denormalized);
  }

  /**
   * Data provider for testDenormalizeUserFormats.
   *
   * @return array
   *   An array of test data.
   */
  public static function providerTestDenormalizeUserFormats() {
    $data = [];

    $data['Y/m/d H:i:s P'] = [
      '2016/11/06 09:02:00 +00:00',
      'Y/m/d H:i:s P',
      new \DateTimeImmutable('2016-11-06T09:02:00+00:00'),
    ];
    $data['H:i:s Y/m/d P'] = [
      '09:02:00 2016/11/06  +01:00',
      'H:i:s Y/m/d P',
      new \DateTimeImmutable('2016-11-06T09:02:00+01:00'),
    ];
    $data['Y/m/d H:i:s'] = [
      '09:02:00 2016/11/06',
      'H:i:s Y/m/d',
      new \DateTimeImmutable('2016-11-06T09:02:00+11:00'),
    ];

    return $data;
  }

  /**
   * Tests the denormalize function with bad data.
   */
  public function testDenormalizeException(): void {
    $this->expectException(UnexpectedValueException::class);
    $this->expectExceptionMessage('The specified date "2016/11/06 09:02am GMT" is not in an accepted format: "Y-m-d\TH:i:sP" (RFC 3339), "Y-m-d\TH:i:sO" (ISO 8601).');

    $normalized = '2016/11/06 09:02am GMT';

    $this->normalizer->denormalize($normalized, DateTimeInterface::class, NULL, []);
  }

  /**
   * Generate test data for date data providers.
   *
   * @return array
   *   Test data for time formats supported by DateTimeNormalizer.
   */
  public static function jsonSchemaDataProvider(): array {
    $case = function (UnitTestCase $test) {
      $drupal_date_time = $test->prophesize(DateTimeNormalizerTestDrupalDateTime::class);
      $drupal_date_time->setTimezone(new \DateTimeZone('Australia/Sydney'))
        ->willReturn($drupal_date_time->reveal());
      $drupal_date_time->format(\DateTime::RFC3339)
        ->willReturn('1983-07-12T05:00:00-05:00');

      $data = $test->prophesize(DateTimeInterface::class);
      $data->getDateTime()
        ->willReturn($drupal_date_time->reveal());
      return $data->reveal();
    };
    return [
      'RFC 3339' => [fn (UnitTestCase $test) => $case($test)],
    ];
  }

}


/**
 * Provides a test class for testing DrupalDateTime.
 *
 * Note: Prophecy does not support magic methods. By subclassing and specifying
 * an explicit method, Prophecy works.
 *
 * @see https://github.com/phpspec/prophecy/issues/338
 * @see https://github.com/phpspec/prophecy/issues/34
 * @see https://github.com/phpspec/prophecy/issues/80
 */
class DateTimeNormalizerTestDrupalDateTime extends DrupalDateTime {

  /**
   * Sets the timezone.
   */
  public function setTimezone(\DateTimeZone $timezone) {
    parent::setTimezone($timezone);
  }

}
