<?php declare(strict_types=1);


namespace Newland\Toubiz\Sync\Neos\Orm\Uuid;

use Doctrine\ORM\EntityManager;
use Newland\Toubiz\Sync\Neos\Domain\Model\AbstractEntity;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;

class UuidGenerator extends \Doctrine\ORM\Id\UuidGenerator
{

    public static function uuidFromProperties(array $properties): UuidInterface
    {
        return Uuid::uuid5(Uuid::NIL, implode('|', $properties));
    }

    /**
     * @param mixed $entity
     * @return mixed
     */
    public function generate(EntityManager $em, $entity)
    {
        return $this->existingIdentifierIfAvailable($entity)
            ?? $this->generatedUuidIfCustomUuidGenerationImplemented($entity)
            ?? parent::generate($em, $entity);
    }

    /**
     * @param mixed $entity
     */
    private function existingIdentifierIfAvailable($entity): ?string
    {
        if ($entity instanceof AbstractEntity || method_exists($entity, 'getPersistenceObjectIdentifier')) {
            return $entity->getPersistenceObjectIdentifier();
        }
        return null;
    }

    /**
     * @param mixed $entity
     */
    private function generatedUuidIfCustomUuidGenerationImplemented($entity): ?string
    {
        if ($entity instanceof CustomUuidGeneration) {
            return $entity->generateUuid()->toString();
        }
        return null;
    }
}
