<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Domain\Repository;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Persistence\Doctrine\Repository;
use Newland\Toubiz\Sync\Neos\Domain\Model\RecordConfiguration;
use Newland\Toubiz\Sync\Neos\Domain\Model\RecordConfigurationSubject;

/**
 * @Flow\Scope("singleton")
 */
class RecordConfigurationRepository extends Repository
{

    public function forRecord(RecordConfigurationSubject $record): RecordConfiguration
    {
        /** @var RecordConfiguration|null $configuration */
        $configuration = $this->findByIdentifier($record->getPersistenceObjectIdentifier());
        return $configuration ?? new RecordConfiguration();
    }

    public function updateConfiguration(
        RecordConfigurationSubject $record,
        callable $modifier,
        bool $persistRecord = true
    ): void {
        $recordConfiguration = $this->forRecord($record);
        $isNew = $recordConfiguration->getPersistenceObjectIdentifier() === null;

        $recordConfiguration->setPersistenceObjectIdentifier((string) $record->getPersistenceObjectIdentifier());
        $recordConfiguration->setConfiguration($modifier($recordConfiguration->getConfiguration()));

        if ($isNew) {
            $this->add($recordConfiguration);
        } else {
            $this->update($recordConfiguration);
        }

        $this->applyRecordConfigurationToRecord($record, $persistRecord, $recordConfiguration);
    }

    public function applyRecordConfigurationToRecord(
        RecordConfigurationSubject $record,
        bool $persistRecord = true,
        RecordConfiguration $configuration = null
    ): void {
        $record->applyRecordConfiguration($configuration ?? $this->forRecord($record));

        if ($persistRecord) {
            $this->entityManager->persist($record);
        }
    }
}
