<?php declare(strict_types=1);

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

use Neos\Flow\Tests\FunctionalTestCase;
use Neos\Flow\Utility\Now;
use Newland\Toubiz\Sync\Neos\Domain\Model\Weather;
use Newland\Toubiz\Sync\Neos\Domain\Repository\WeatherRepository;
use Newland\Toubiz\Sync\Neos\Importer\WeatherImporter;
use Newland\Toubiz\Sync\Neos\Tests\Factory\WeatherFactory;
use Newland\Toubiz\Sync\Neos\Tests\Unit\Importer\Mock\DayAdapterMock;
use Newland\Toubiz\Sync\Neos\Tests\Unit\Importer\Mock\WeatherAdapterMock;

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

    /** @var WeatherRepository */
    protected $repository;

    public function setUp(): void
    {
        parent::setUp();
        $this->repository = $this->objectManager->get(WeatherRepository::class);
    }

    public function testCreatesNewDatabaseRecordIfLocationNotFound(): void
    {
        $this->assertNull($this->repository->findOneBy([ 'location' => 'foo' ]));
        (new WeatherImporter())->import(new WeatherAdapterMock([ 'location' => 'foo' ]));
        $this->assertNotNull($this->repository->findOneBy([ 'location' => 'foo' ]));
    }

    public function testReusesDatabaseRecordIfLocationFound(): void
    {
        $existing = (new WeatherFactory($this->objectManager))->create([ 'location' => 'bar' ]);
        $imported = (new WeatherImporter())->import(new WeatherAdapterMock([ 'location' => 'bar' ]));
        $this->assertEquals($existing->getPersistenceObjectIdentifier(), $imported->getPersistenceObjectIdentifier());
    }

    public function testSetsUpdatedAtToCurrentTimestamp(): void
    {
        (new WeatherFactory($this->objectManager))->create([
            'location' => 'hello',
            'updatedAt' => new \DateTime('2017-01-01T01:01:01')
        ]);

        $this->objectManager->setInstance(Now::class, new Now('2019-01-02T13:55:00'));
        (new WeatherImporter())->import(new WeatherAdapterMock([ 'location' => 'hello' ]));

        $fromDb = $this->repository->findOneBy([ 'location' => 'hello' ]);
        $this->assertEquals('2019-01-02__13:55:00', $fromDb->getUpdatedAt()->format('Y-m-d__H:i:s'));
    }

    public function testUpdatesDataWhenUpdatingRecord(): void
    {
        $created = (new WeatherFactory($this->objectManager))->create([
            'location' => 'baz',
            'data' => new WeatherAdapterMock([ 'forecast' => [] ]),
        ]);
        $this->assertCount(0, $created->getForecast());

        (new WeatherImporter())->import(new WeatherAdapterMock([
              'location' => 'baz',
              'forecast' => [ new DayAdapterMock([ ]) ]
        ]));
        $fromDb = $this->repository->findOneBy([ 'location' => 'baz' ]);
        $this->assertCount(1, $fromDb->getForecast());
    }

}
