<?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\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Serenity\MediaBundle\Entity\Attachment;
use Symfony\Component\Validator\Constraints as Assert;

trait MediasTrait
{
    #[Assert\Valid]
    public Collection $files;

    private bool $filesInitialized = false;

    /** @var callable|null */
    private $filesLoader;

    public function __construct()
    {
        $this->files = new ArrayCollection();
    }

    /**
     * @return Collection<int, Attachment>
     */
    public function getFiles(): Collection
    {
        if (!$this->filesInitialized && $this->filesLoader) {
            $this->files = new ArrayCollection(($this->filesLoader)($this));
            $this->filesInitialized = true;
        }

        return $this->files;
    }

    public function setFilesFromPostLoad(array $files): void
    {
        $this->files = new ArrayCollection($files);
        $this->filesInitialized = true;
    }

    public function setFilesLoader(?callable $loader): void
    {
        $this->filesLoader = $loader;
    }

    public function addFile(Attachment $attachment): void
    {
        if (!$this->files->contains($attachment)) {
            $this->files->add($attachment);
            if (method_exists($this, 'getId') && $this->getId()) {
                $attachment->setParentId($this->getId());
            }
            $attachment->setParentClass(static::class);
        }
    }

    public function removeFile(Attachment $attachment): void
    {
        if ($this->files->removeElement($attachment)) {
            if ($attachment->getParentId() && $attachment->getParentClass()) {
                $attachment->setParentId(null);
                $attachment->setParentClass(null);
            }
        }
    }
}
