<?php

/**
 * @author Colinet Julien
 */
declare(strict_types=1);

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\MediaBundle\Trait;

use Doctrine\ORM\Mapping as ORM;
use Serenity\MediaBundle\Attribute\Attachment;
use Serenity\MediaBundle\Entity\Image;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

trait ImageMandatoryTrait
{
    #[Assert\Valid]
    #[ORM\OneToOne(targetEntity: Image::class, cascade: ['all'])]
    #[ORM\JoinColumn(name: 'image_id', referencedColumnName: 'id', onDelete: 'SET NULL')]
    #[Attachment]
    private ?Image $image = null;

    public function getImage(): ?Image
    {
        return $this->image;
    }

    public function setImage(?Image $image): void
    {
        if (null === $image) {
            return;
        }
        if (!$image->getUploadedFile() && !$image->getFile()->getName()) {
            $this->image = null;

            return;
        }
        $this->image = $image;
    }

    #[Assert\Callback]
    public function validate(ExecutionContextInterface $context, $payload): void
    {
        if (!$this->getImage() || (!$this->getImage()->getFile() && !$this->getImage()->getUploadedFile())) {
            $context->buildViolation('This value should not be blank.')
              ->atPath('image.uploadedFile')
              ->addViolation();
        }
    }
}
