<?php

/**
 * @author Victor Zamfir
 */

class vzMenuComposite implements Countable, Iterator
{
  protected
    $_id                      = null,
    $_positions               = array(),
		$_parent                  = null;
		
  public function __construct($id = null)
  {
    $this->setId($id);
    $this->getManager()->add($this);
  }
  
  public function getId()
  {
    return $this->_id;
  }
  
  public function setId($id)
  {
    $this->_id = $id;
    return $this;
  }
  
  public function getParent($levels_up = 1)
  {
    $parent = $this->hasParent() ? $this->getFromManager($this->_parent) : null;
    $levels_up--;
    while ($levels_up && $parent)
    {
      $parent = $parent->getParent();
      $levels_up--;
    }
    return $parent;
  }
  
  public function setParent(vzMenu $parent)
  {
    $this->_parent = $parent->getId();
    return $this;
  }
  
  public function hasParent()
  {
    return !is_null($this->_parent);
  }
  
  protected function getManager()
  {
    return sfContext::getInstance()->getMenuManager();
  }
  
  protected function getFromManager($id = null)
  {
    return $this->getManager()->get(is_null($id) ? $this->getId() : $id);
  }
  
  public function add($child, $position = 'last', $pivot = null)
  {
    $child = $this->introspectChild($child);
    
    $id = $child->getId();
		
		switch ($position)
    {
      case 'first':
        array_unshift($this->_positions, $id);
      break; 
      
      case 'last':
        $this->_positions[] = $id;
      break;
      
      case 'after':
        if ($pivot)
        {
        	$pivotPosition = $this->findChildPosition($pivot);
          if ($pivotPosition === false)
          {
            throw new sfException(sprintf('non-existent child pivot'));
          }
					
          $this->_positions = array_merge(
            array_slice($this->_positions, 0, $pivotPosition + 1),
            array($id),
            array_slice($this->_positions, $pivotPosition + 1)
          );
        } else {
					throw new sfException('you must specify a pivot');        	
        }
      break;
      
      case 'before':
        if ($pivot) 
        {
          $pivotPosition = $this->findChildPosition($pivot);
          if ($pivotPosition === false)
          {
            throw new sfException(sprintf('non-existent child pivot'));
          }
					
          $this->_positions = array_merge(
            array_slice($this->_positions, 0, $pivotPosition),
            array($id),
            array_slice($this->_positions, $pivotPosition)
          );
					
        } else {
					throw new sfException('you must specify a pivot');        	
        }
      break;
		}
		
		$child->setParent($this);
		return $child;
  }
  
  protected function introspectChild($child)
  {
    if (!(is_object($child) && ($child instanceof vzMenuComposite)))
    {
      $child = new vzMenuComposite($child);
    }
    
    return $child;
  }
  
  protected function findChildPosition($child)
  {
    if (is_object($child))
    {
      if (!$child instanceof vzMenuComposite)
      {
        throw new sfException('invalid child object');
      }
      
      foreach ($this->_positions as $pos => $child_id) {
			  if ($child->getId() == $child_id) {
				  return $pos;
			  }
		  }
    }
    
    return false;
  }
  
  public function addTo(vzMenuComposite $parent)
	{
		$parent->add($this);
		return $this;
	}
	
	public function hasChildren()
  {
    return count($this->_positions);
  }
  
  public function getChildren()
  {
    $children = array();
    foreach ($this->_positions as $position)
    {
      $children[] = $this->getFromManager($position);
    }
    return $children;
  }
  
  public function move($position, $pivot = null)
  {
    if (!($parent = $this->getParent()))
    {
      return;
    }
    
    switch ($position)
    {
      case 'first':
      	if (!$this->isFirst())
        {
          array_splice($parent->_positions, $parent->findChildPosition($this), 1);
          array_unshift($parent->_positions, $this->getId());
        }
      break;
      case 'last':
      	if (!$this->isLast())
        {
          array_splice($parent->_positions, $parent->findChildPosition($this), 1);
          array_push($parent->_positions, $this->getId());
        }
      break;
      case 'before':
      	if (!$pivot)
        {
          throw new sfException('you must specify a pivot');
        }
        
      	$pivot_position = $parent->findChildPosition($pivot);
        if ($pivot_position === false)
        {
          throw new sfException(sprintf('non-existent child pivot'));
        }
        
        if ($pivot->getPrevious()->getId() == $this->getId())
        {
          return;
        }
        
        array_splice($parent->_positions, $parent->findChildPosition($this), 1);
          
        $parent->_positions = array_merge(
          array_slice($parent->_positions, 0, $pivot_position),
          array($this->getId()),
          array_slice($parent->_positions, $pivot_position)
        );
      break;
      case 'after':
      	if (!$pivot)
        {
          throw new sfException('you must specify a pivot');
        }
        
        $pivot_position = $parent->findChildPosition($pivot);
        if ($pivot_position === false)
        {
          throw new sfException(sprintf('non-existent child pivot'));
        }
        
        if ($pivot->getNext()->getId() == $this->getId())
        {
          return;
        }
        
        array_splice($parent->_positions, $parent->findChildPosition($this), 1);
          
        $parent->_positions = array_merge(
          array_slice($parent->_positions, 0, $pivot_position + 1),
          array($this->getId()),
          array_slice($parent->_positions, $pivot_position + 1)
        );
      break;
      
      default:
        throw new DomainException(sprintf('the specified position (%s) is not one of these values: first, last, before, after', $position));
      break;
    }
    
  }
  
  #navigation
	public function getPrevious()
	{
		$position = $this->getParent()->findChildPosition($this);
		if ($position > 0) {
			return $this->getFromManager($this->getParent()->_positions[$position-1]);
		}		
	}
	
	public function getNext()
	{
		$position = $this->getParent()->findChildPosition($this);
		if ($position < count($this->getParent()) - 1) {
			return $this->getFromManager($this->getParent()->_positions[$position+1]);
		}
	}
	
	public function getFirst()
	{
		return $this->hasChildren() ? $this->getFromManager($this->_positions[0]) : null;
	}
	
	public function getLast()
	{
		return $this->hasChildren() ? $this->getFromManager($this->_positions[count($this->_positions) - 1]) : null;
	}
	
	public function isLast()
	{
		if (!$this->hasParent()) {
			return false;
		}
		
		return ($this->getParent()->getLast()->getId() == $this->getId()); 
	}
	
	public function isFirst()
	{
    if (!$this->hasParent()) {
			return false;
		}
		
		return ($this->getParent()->getFirst()->getId() == $this->getId());
	}
	
	#iterator
	public function current()
  {
    return $this->getFromManager(current($this->_positions));
  }

  public function next()
  {
    return next($this->_positions);
  }

  public function key()
  {
    return key($this->_positions);
  }

  public function valid()
  {
    return $this->current();
  }

  public function rewind()
  {
    return reset($this->_positions);
  }
	
	#countable
  public function count()
  {
    return count($this->_positions);
  }
  
  public function __unset($child)
  {
    unset($this[$child]);
  }
} 
