<?php

namespace AutoAdmin\Bundle\BrickBuilder\Storage;

use Doctrine\ORM\EntityManagerInterface;
use Exception;

class ObjectSettingFormat
{
    public function __construct(
        protected EntityManagerInterface $em,
    ) {
    }

    public function objectToString(?object $object): ?string
    {
        if (is_null($object) || empty($object->getId())) {
            return null;
        }

        return get_class($object).'#'.$object->getId();
    }

    public function stringToObject(?string $stringObject): ?object
    {
        if (is_null($stringObject)) {
            return null;
        }

        if ($this->isValidObjectString($stringObject) === false) {
            throw new Exception('Could not extract class and identifier from "'.$stringObject.'"');
        }

        [$class, $identifier] = explode('#', $stringObject);

        $repo = $this->em->getRepository($class);

        return $repo->find($identifier);
    }

    public function isValidObjectString(?string $stringObject): bool
    {
        if (is_null($stringObject)) {
            return false;
        }

        return (bool)preg_match('/^.+#\d+$/', $stringObject);
    }
}
