<?php

namespace AutoAdmin\Bundle\Content\Hierarchy\Model\Traits;

use AutoAdmin\Bundle\Content\Hierarchy\Model\Interfaces\SelfHierarchyInterface;
use AutoAdmin\Bundle\Content\Model\PageInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

trait SelfHierarchyTrait
{
    // doctrine "targetEntity" self::class should be overridden by inherited class
    #[ORM\ManyToOne(targetEntity: self::class, inversedBy: 'children')]
    protected ?SelfHierarchyInterface $parent = null;

    // doctrine "targetEntity" self::class should be overridden by inherited class
    #[ORM\OneToMany(mappedBy: 'parent', targetEntity: self::class)]
    protected Collection $children;

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

    public function getParent(): ?SelfHierarchyInterface
    {
        return $this->parent;
    }

    public function setParent(?SelfHierarchyInterface $parent): SelfHierarchyInterface
    {
        $this->parent = $parent;

        return $this;
    }

    public function getChildren(): Collection
    {
        return $this->children;
    }

    public function setChildren(Collection $children): SelfHierarchyInterface
    {
        $this->children = $children;

        return $this;
    }

    public function addChild(SelfHierarchyInterface $child): SelfHierarchyInterface
    {
        if (!$this->children->contains($child)) {
            $this->children[] = $child;
            $child->setParent($this);
        }

        return $this;
    }

    public function removeChild(SelfHierarchyInterface $child): SelfHierarchyInterface
    {
        if ($this->children->removeElement($child) && $child->getParent() === $this) {
            $child->setParent(null);
        }

        return $this;
    }
}
