<?php

namespace App\Entity;

use App\Entity\Helpers\TrackedTrait;
use App\Repository\SnipRepository;
use App\Service\SnipContent\SnipContentService;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: SnipRepository::class)]
class Snip
{
    use TrackedTrait;

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    public ?int $id = null;

    #[ORM\Column(length: 255)]
    public ?string $name = null;

    #[ORM\Column]
    public bool $public = false;

    #[ORM\OneToMany(targetEntity: SnipContent::class, mappedBy: 'snip', orphanRemoval: true)]
    public Collection $snipContents;

    #[ORM\OneToOne]
    public ?SnipContent $activeVersion = null;

    #[ORM\Column(length: 255)]
    public ?string $parser = null;

    #[ORM\Column]
    public bool $visible = true;

    #[ORM\Column]
    public bool $archived = false;

    /**
     * @var Collection<int, Tag>
     */
    #[ORM\ManyToMany(targetEntity: Tag::class, mappedBy: 'snips')]
    public Collection $tags;

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

    public function __toString(): string
    {
        return $this->name ?? '';
    }

    public function getActiveText(): string
    {
        return SnipContentService::rebuildText($this->activeVersion);
    }

    public function addSnipContent(SnipContent $snipContent): self
    {
        if (!$this->snipContents->contains($snipContent)) {
            $this->snipContents->add($snipContent);
            $snipContent->snip = $this;
        }

        return $this;
    }

    public function removeSnipContent(SnipContent $snipContent): self
    {
        if ($this->snipContents->removeElement($snipContent)) {
            // set the owning side to null (unless already changed)
            if ($snipContent->snip === $this) {
                $snipContent->snip = null;
            }
        }

        return $this;
    }

    public function getLatestVersion(): ?SnipContent
    {
        return $this->snipContents->last() ?: null;
    }

    public function addTag(Tag $tag): static
    {
        if (!$this->tags->contains($tag)) {
            $this->tags->add($tag);
            $tag->addSnip($this);
        }

        return $this;
    }

    public function removeTag(Tag $tag): static
    {
        if ($this->tags->removeElement($tag)) {
            $tag->removeSnip($this);
        }

        return $this;
    }
}
