<?php


namespace AutoAdmin\Bundle\Content\Entity;

use AutoAdmin\Bundle\Content\Entity\Traits\TranslatableTrait;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Model\TranslationInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use InvalidArgumentException;

/**
 * Class ContentTranslation
 *
 * @package AutoAdmin\Bundle\Entity\Content
 *
 * @method _tr(): ?TranslationInterface
 */
#[ORM\MappedSuperclass]
abstract class AbstractTranslatable extends AbstractUntranslated implements TranslatableInterface
{
    use TranslatableTrait;

    /**
     * Annotation will be generated dynamically:
     * ORM\OneToMany(targetEntity="", mappedBy="translatable", cascade={"ALL"}, orphanRemoval=true)
     */
    protected Collection $translations;

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

    public function __call($name, $arguments)
    {
        if ($name === '_tr') {
            return $this->getCurrentTranslation();
        }
        throw new InvalidArgumentException('Method "' . $name . '" does not exist in class "' . get_class($this) . '"');
    }

    /**
     * This is important, as form has default option: by_reference = false
     * so here we set the mapped side entity.
     */
    public function addTranslation(TranslationInterface $translation): void
    {
        $this->getTranslations()->add($translation);
        $translation->setTranslatable($this);
    }

    public function getTranslations(?string $locale = null): Collection
    {
        if ($locale == null) {
            return $this->translations;
        }

        return $this->translations->filter(
            function (TranslationInterface $translation) use ($locale) {
                return $translation->getLocale()->getCode() === $locale;
            }
        );
    }

    /**
     * This is also used by form.
     */
    public function removeTranslation(TranslationInterface $translation): void
    {
        $this->getTranslations()->removeElement($translation);
    }
}
