<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Tests\Unit\Importer;

use Neos\Flow\Tests\FunctionalTestCase;
use Newland\Toubiz\Sync\Neos\Importer\EventDateImporter;
use Newland\Toubiz\Sync\Neos\Tests\Factory\EventDateFactory;
use Newland\Toubiz\Sync\Neos\Tests\Unit\Importer\Mock\EventDateAdapterMock;

class EventDateImporterTest extends FunctionalTestCase
{
    protected static $testablePersistenceEnabled = true;

    /** @var EventDateImporter */
    protected  $subject;

    /** @var EventDateFactory */
    protected $factory;

    public function setUp(): void
    {
        parent::setUp();
        $this->subject = $this->objectManager->get(EventDateImporter::class);
        $this->factory = new EventDateFactory($this->objectManager);
    }

    public function testReusesGivenModelIfSpecified(): void
    {
        $date = $this->factory->create();
        $imported = $this->subject->import(new EventDateAdapterMock([ ]), $date);

        $this->assertEquals($imported->getPersistenceObjectIdentifier(), $date->getPersistenceObjectIdentifier());
    }

    public function testUsingSameExternalIdAsExistingModelDoesNotAutomaticallyReuseIt(): void
    {
        $date = $this->factory->create([ 'language' => 'de' ]);
        $this->subject->setLanguage('en');
        $imported = $this->subject->import(new EventDateAdapterMock([ 'externalId' => $date->getOriginalId() ]), null);

        $this->assertNotEquals($imported->getPersistenceObjectIdentifier(), $date->getPersistenceObjectIdentifier());
    }

    public function testUsingSameExternalIdDoesNotYieldSameModel(): void
    {
        $this->subject->setLanguage('de');
        $first = $this->subject->import(new EventDateAdapterMock([ 'externalId' => 'foo' ]), null);
        $this->subject->setLanguage('en');
        $second = $this->subject->import(new EventDateAdapterMock([ 'externalId' => 'foo' ]), null);

        $this->assertNotEquals($first->getPersistenceObjectIdentifier(), $second->getPersistenceObjectIdentifier());
    }

    public function testMapsDates(): void
    {
        $adapter = new EventDateAdapterMock([
            'externalId' => 'foo',
            'beginsAt' => new \DateTime('2020-01-01T15:00:00'),
            'beginsAtSpecificTime' => true,
            'endsAt' => new \DateTime('2020-01-01T23:59:59'),
            'endsAtSpecificTime' => false,
        ]);

        $date = $this->subject->import($adapter, null);

        $this->assertTrue($date->getBeginsAtSpecificTime());
        $this->assertFalse($date->getEndsAtSpecificTime());
        $this->assertEquals('2020-01-01 15:00:00', $date->getBeginsAt()->format('Y-m-d H:i:s'));
        $this->assertEquals('2020-01-01 23:59:59', $date->getEndsAt()->format('Y-m-d H:i:s'));
    }
}
