<?php declare(strict_types=1);

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

use Neos\Flow\Tests\FunctionalTestCase;
use Newland\Toubiz\Sync\Neos\Domain\Model\Medium;
use Newland\Toubiz\Sync\Neos\Importer\MediumImporter;
use Newland\Toubiz\Sync\Neos\Tests\Factory\MediaFactory;
use Newland\Toubiz\Sync\Neos\Tests\Unit\Importer\Mock\MediaAdapterMock;

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

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

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

    public function setUp(): void
    {
        parent::setUp();
        $this->subject = $this->objectManager->get(MediumImporter::class);
        $this->subject->setDownload(false);
        $this->factory = new MediaFactory($this->objectManager);
    }

    public function testReusesGivenModel(): void
    {
        $media = $this->factory->create();
        $adapter = new MediaAdapterMock([ 'title' => '__FOO__' ]);

        $this->subject->import($adapter, $media);

        $fromDb = $this->persistenceManager->getObjectByIdentifier($media->getPersistenceObjectIdentifier(), Medium::class);
        $this->assertNotNull($fromDb);
        $this->assertEquals('__FOO__', $fromDb->getTitle());
        $this->assertEquals('__FOO__', $media->getTitle());
    }


    public function testCreatesNewAddressIfNoneGiven(): void
    {
        $adapter = new MediaAdapterMock([ 'title' => '__BAR__' ]);
        $imported = $this->subject->import($adapter, null);

        $fromDb = $this->persistenceManager->getObjectByIdentifier($imported->getPersistenceObjectIdentifier(), Medium::class);
        $this->assertNotNull($fromDb);
        $this->assertEquals('__BAR__', $fromDb->getTitle());
    }

    public function testTwoAddressesWithSameExternalIdDoNotOverwriteEachOther(): void
    {
        $one = $this->subject->import(new MediaAdapterMock([ 'externalId' => 'test' ]));
        $two = $this->subject->import(new MediaAdapterMock([ 'externalId' => 'test' ]));

        $this->assertNotNull($one);
        $this->assertNotNull($two);
        $this->assertNotEquals($one->getPersistenceObjectIdentifier(), $two->getPersistenceObjectIdentifier());
    }

}
