<?php

namespace Comitium5\DesignerBundle\Model\Traits\Node;

use Comitium5\DesignerBundle\Model\Interfaces\Node\NodeInterface;
use Doctrine\Common\Collections\ArrayCollection;


/**
 * Class NodeTrait
 *
 * @author Fernando Pradas <fernando@bab-soft.com>
 * @package Comitium5\DesignerBundle\Model\Traits\Node
 */
trait NodeTrait
{

    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    protected $children;

    /**
     * @var NodeInterface
     */
    protected $parent;

    /**
     * @var int
     */
    protected $pointer;


    /**
     * @param NodeInterface $child
     * @return $this
     */
    public function addChild(NodeInterface $child)
    {
    	if (!$this->children->contains($child)) {
	        $child->setParent($this);
	        $this->children->add($child);
		}

        return $this;
    }

    /**
     * @param NodeInterface $child
     */
    public function removeChild(NodeInterface $child)
    {
        $this->children->removeElement($child);
    }

    /**
     * @{inherit}
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * @return bool
     */
    public function hasChildren()
    {
        return !$this->children->isEmpty();
    }

    /**
     * @param ArrayCollection $children
     * @return $this
     */
    public function setChildren(ArrayCollection $children)
    {
        $this->children = $children;

        return $this;
    }

    /**
     * @param NodeInterface $parent
     * @return $this
     */
    public function setParent(NodeInterface $parent = null)
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * @{inherit}
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * @{inherit}
     */
    public function rewind()
    {
        $this->pointer = 0;
    }

    /**
     * @{inherit}
     */
    public function current()
    {
        if(null == $this->pointer)
            $this->rewind();

        return $this->children[$this->pointer];
    }

    /**
     * @{inherit}
     */
    public function key()
    {
        if(null == $this->pointer)
            $this->rewind();

        return $this->pointer;
    }

    /**
     * @{inherit}
     */
    public function next()
    {
        if(null == $this->pointer)
            $this->rewind();

        ++$this->pointer;
    }

    /**
     * @{inherit}
     */
    public function valid()
    {
//        if(null == $this->pointer)
//            $this->rewind();
//
//        return isset($this->children[$this->pointer]);
    }


}