<?php 

namespace App\Form\DataTransformer;

use App\Entity\Photo;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\HttpFoundation\File\File;

class UploadDataTransformer implements DataTransformerInterface
{
    public function __construct(private EntityManagerInterface $entityManager) {}

    public function transform($photo) : string
    {
        if ($photo === null) {
            return '';
        }

        return $photo;
    }

    public function reverseTransform($filename): ?File
    {
        if (!$filename) {
            return null;
        }

        $photo = $this->entityManager->getRepository(Photo::class)->findOneBy(['file' => $filename]);

        $directoryName = $photo->getPhotos()->getTitle();

        $directoryName = 'photos/' . strtolower(str_replace(' ', '_', $directoryName));

        $file = new File($directoryName . '/' . $filename);

        if ($file === null) {
            throw new TransformationFailedException(sprintf('Photo with the filename "%s" does not exist!', $filename));
        }

        return $file;
    }
}