<?php

/**
 * @author Victor Zamfir
 */
 
/**
 * TODO
 *  - de imbunatatit metoda de remove
 *
 */
 
class vzMenu extends vzMenuComposite implements ArrayAccess
{
  static
    $ACTIVE_CLASS_NAME = 'active',
    $DEFAULT_RENDERER  = 'vzMenuRenderer';

  protected
    $_label                   = null,
    $_link                    = null,
    $_name                    = null,
		$_attributes              = array(),
		$_storage                 = array(),
		$_template                = '%s',
		$_matching                = array(
			'modules' 			=> array(),
			'routes'				=> array(),
			'module.action' => array()
		),
		$_is_active               = false,
		$_active_child            = null,
		$_is_parsed               = false,
		$_requires_authentication = false,
		$_credentials             = array();

  public function __construct($label = null, $link = null, $id = null)
  {
    if (is_array($label))
    {
      list($label, $link, $id) = array_pad($label, 3, null);
    }
  
    $this
      ->setLabel($label)
      ->setLink($link);
      
    parent::__construct($id);
    
    $this->configure();
  }
  
  protected function configure()
  {
  }
  
  public function getLabel()
  {
    return $this->_label;
  }
  
  public function setLabel($label)
  {
    $this->_label = $label;
    if (!$this->getName()) {
			$this->setName($label);
		}
    return $this;
  }
  
  public function getName()
  {
    return $this->_name;
  }
  
  public function setName($name)
  {
		$this->_name = vzMenuInflector::underscoreize($name);
		return $this;
  }
  
  public function getLink()
  {
    return $this->_link;
  }
  
  public function setLink($link)
  {
    $this->_link = $link;
    
    $this->_matching = array(
			'modules' 			=> array(),
			'routes'				=> array(),
			'module.action' => array()
		);
		$this->isActiveFor($link);
    
    return $this;
  }
  
  public function getIdAttribute($separator = '_')
  {
    if ($this->hasParent())
    {
      return $this->getParent()->getIdAttribute() . $separator . $this->getName();
    }
    else
    {
      return $this->getName();
    }
  }
  
  protected function introspectChild($child)
  {
    if (!(is_object($child) && ($child instanceof vzMenu)))
    {
      $child = new vzMenu($child);
    }
    
    return $child;
  }
  
  protected function findChildPosition($child)
  {
    if (is_object($child))
    {
      return parent::findChildPosition($child);
    }
    else if (is_string($child))
    {
      foreach ($this->_positions as $pos => $child_id) {
			  if ($child == $this->getFromManager($child_id)->getName()) {
				  return $pos;
			  }
		  }
    }
    else
    {
      throw new sfException('invalid child parameter');
    }
    
    return false;
  }
  
  public function get($string)
	{
		$names_array = explode('.', $string);
		
		if (count($names_array) == 1)
		{
		  $name = $names_array[0];
		  foreach ($this->_positions as $id)
		  {
		    if ($this->getFromManager($id)->getName() == $name)
		    {
		      return $this->getFromManager($id);
		    }
		  }
		  
		  return false;
		}
		
		$current_menu = $this;
		
		do {
			$child_name = $names_array[0];
			if (!$current_menu = $current_menu->get($child_name))
			{
			  return false;
			}
			array_shift($names_array);
		} while (count($names_array));
		
		return $current_menu;
	}
  
  public function delete()
  {
//    $this->remove(array_values($this->_positions), true);
//    $this->getManager()->remove($this->getId());
  }
  
  public function remove(array $children, $with_delete = true)
	{
		foreach ($children as $child) {
			$pos = $this->findChildPosition($child);
			if ($pos !== false) {
			  $child = $this->getFromManager($child);
			  if ($with_delete)
			  {
			    $child->delete();
			  }
			  
				if ($pos == 0) {
					array_shift($this->_positions);
				} else {
					array_splice($this->_positions, $pos, 1);					
				}
			}
		}
		return $this;
	}
	
	
	#array access
	public function offsetExists($name)
  {
    return !$this->get($name);
  }

  public function offsetGet($name)
  {
  	return $this->get($name);
  }

  public function offsetSet($name, $value)
  {
  	if ($menu = $this->get($name)) {
  		return $menu->setLabel($value);
  	}
    return $this->add($name);
  }

  public function offsetUnset($name)
  {
  	$this->remove($name);
  }
  
  #magic
	public function __call($method, $arguments)
	{
	  $dispatcher = sfContext::getInstance()->getEventDispatcher();
    
		$event = $dispatcher->notifyUntil(new sfEvent($this, 'vz_menu.method_not_found', array(
      'method'    => $method, 
      'arguments' => $arguments
    )));
    if (!$event->isProcessed())
    {
      throw new sfException(sprintf('Call to undefined method %s::%s.', get_class($this), $method));
    }
 
    return $event->getReturnValue();
	}
	
	public function __get($name)
	{
		return $this[$name];
	}
	
	public function __set($name, $value)
	{
		$this[$name] = $value;
	}
	
	
	/* bof $attributes */
	public function addAttributes(array $attributes)
	{
	  $this->_attributes = array_merge($this->_attributes, $attributes);
		return $this;
	}
	
	public function setAttributes(array $attributes)
	{
		$this->_attributes = $attributes;
		return $this;
	}
	
	public function setAttribute($key, $value)
	{
		$this->_attributes[$key] = $value;
		return $this;
	}
	
	public function hasAttribute($key)
	{
	  return isset($this->attributes[$key]);
	}
	
	public function getAttributes()
	{
		return $this->_attributes;
	}
	
	public function getAttribute($key)
	{
		if (isset($this->_attributes[$key])) {
			return $this->_attributes[$key];
		}
	}
	/* eof $attributes */
	
	/* bof storage */
	public function store()
	{
		$args = func_get_args();
		if (count($args) == 1) {
			if (!is_array($args[0])) {
				throw new sfException('you must pass an array');
			}
			$this->_storage = array_merge($this->_storage, $args[0]);
		} else if (count($args) == 2) {
			$this->_storage[$args[0]] = $args[1];
		}
		
		return $this;
	}
	
	public function retrieve($key)
	{
		$storage = $this->getStorage();
		return (isset($storage[$key]) ? $storage[$key] : null);
	}
	
	public function getStorage()
	{
		return $this->_storage;
	}
	/* eof storage */
	
	public function setTemplate($template)
	{
		$this->_template = $template;
		return $this;
	}
	
	public function getTemplate()
	{
		return $this->_template;
	}
	
	public function getPathAsArray($tpl)
	{
		$path = array();
		$obj = $this;
		do {
			$path[] = sprintf($tpl ? $tpl : $this->getTemplate(), $obj->getLabel());
		} while ($obj = $obj->getParent());
		
		return array_reverse($path);
	}
	
	public function getPathAsString($separator = ' > ', $tpl = '<span>%s</span>')
	{
    return implode($separator, $this->getPathAsArray($tpl));
	}
	
	public function callRecursively($callback)
  {
    call_user_func($callback, $this);

    foreach ($this as $child)
    {
      $child->callRecursively($callback);
    }

    return $this;
  }
	
	public function fromArray(array $array)
	{
		$this->delete();
		
		if (isset($array['label'])) {
			$this->setLabel($array['label']);
		}
		
		if (isset($array['name'])) {
			$this->setName($array['name']);
		}
		
		if (isset($array['link'])) {
			$this->setLink($array['link']);
		}
		
		if (isset($array['attributes'])) {
			$this->setAttributes($array['attributes']);
		}
		
		if (isset($array['template'])) {
			$this->setTemplate($array['template']);
		}
		
		if (isset($array['storage'])) {
			$this->store($array['storage']);
		}
		
		if (isset($array['children']))
    {
      foreach ($array['children'] as $name => $child)
      {
        $this->add($name)->fromArray($child);
      }
    }
		
		return $this;
	}
	
	public function toArray()
	{
		$array = array();
		
		$array['name'] 				= $this->getName();
		$array['label'] 			= $this->getLabel();
		$array['link'] 				= $this->getLink();
		$array['attributes'] 	= $this->getAttributes();
		$array['template'] 		= $this->getTemplate();
		$array['children'] 		= array();
		 
		if ($this->hasChildren()) {
			foreach ($this as $child) {
				$array['children'][$child->getName()] = $child->toArray();
			}
		}
		
		return $array;
	}
	
	public function __toString()
	{
		return $this->renderContent();
	}
  
	public function renderContent($with_link = true)
	{
		if ($this->retrieve('generated_link')) {
			return $this->retrieve('generated_link');
		}
		
		if ($this->getLink() && $with_link) {
		  $attributes = $this->getAttributes();
      if (!isset($attributes['id']))
      {
        $attributes['id'] = $this->getIdAttribute();
      }
			return link_to(sprintf($this->getTemplate(), $this->getLabel()), $this->getLink(), $attributes);			
		}
		return sprintf($this->getTemplate(), $this->getLabel());
	}
  
  public function render($renderer = false)
  {
    if (!$renderer)
    {
      $renderer = self::$DEFAULT_RENDERER;
    }
    
    return call_user_func($renderer . '::render', $this);
  }
  
  public function __destruct()
  {
//    $this->delete();
  }
  
  /** bof routing **/
  public function isActiveFor()
	{
		foreach (func_get_args() as $link) {
			$this->_parseLink($link);
		}
		return $this;
	}
	
	public function isNotActiveFor()
	{
	  $args = func_get_args();
		return call_user_func_array(array($this, 'isInactiveFor'), $args);
	}
	
	public function isInactiveFor()
	{
		foreach (func_get_args() as $link) {
      $this->_parseLink($link, false);
    }
    return $this;
	}
	
	protected function _parseLink($link, $and_match = true)
	{
		if (substr($link, 0, 1) == '@') { #is a route
		  
		  $route = substr($link, 1, strpos($link, '?') ? strpos($link, '?') - 1 : strlen($link) - 1);
		
		  if ($and_match)
      {
        $this->_matching['routes'][] = $route;
      }
      else
      {
        $offset = array_search($route, $this->_matching['routes']);
        if ($offset !== false)
        {
          array_splice($this->_matching['routes'], $offset, 1);
        }
      }
      
      return;
		}
		
		if (strpos($link, '/')) {
			list($module, $action) = explode('/', $link);
			if ($action == '*') {
			  if ($and_match)
        {
			    $this->_matching['modules'][] = $module;
			  }
        else
        {
          $offset = array_search($module, $this->_matching['modules']);
          if ($offset !== false)
          {
            array_splice($this->_matching['modules'], $offset, 1);
          }
        }
			} else {
			  if ($and_match)
        {
          return $this->_matching['module.action'][] = $link;
        }
        else
        {
          $offset = array_search($link, $this->_matching['module.action']);
          if ($offset !== false)
          {
            array_splice($this->_matching['module.action'], $offset, 1);
          }
        }
			}
		}
	}
  
	public function isActive($bool = null)
	{
	  if (!is_null($bool))
	  {
	    $this->_is_active = (boolean) $bool;
	  }
	  
	  return $this->_is_active;
	}
	
	public function getActiveItem($depth = 1)
	{
		$menu = $this;
		do {
		  if ($menu->_active_child === null)
      {
        return false;
      }
			$menu = $this->getFromManager($menu->_active_child);
			--$depth;
		} while ($depth);
		
		return $menu;
	}
	
	protected function markAsActive()
	{
		$this->setAttribute('class', vzHtmlAttributes::mergeCssClasses(self::$ACTIVE_CLASS_NAME, $this->getAttribute('class')));
	}
	
	public function makeActive()
	{
	  $this->markAsActive();
		$this->isActive(true);
		if ($this->hasParent()) {
			$this->getParent()->_active_child = $this->getId();
			$this->getParent()->makeActive();
		}
		
		return $this;
	}
	
	public function parse()
	{
	  if ($this->_is_parsed)
	  {
	    return;
	  }
    
    foreach ($this->_positions as $child)
    {
      if ($this->getFromManager($child)->parse())
      {
        return true;
      }
    }
	  
	  if (!sfContext::hasInstance()) {
			return;
		}
		
		if (in_array(sfContext::getInstance()->getModuleName(), $this->_matching['modules'])) {
			$this->makeActive();
      return true;
		}
		
		if (in_array(sfContext::getInstance()->getRouting()->getCurrentRouteName(), $this->_matching['routes'])) {
			$this->makeActive();
      return true;
		}
		
		if (in_array(sfContext::getInstance()->getModuleName() . '/' . sfContext::getInstance()->getActionName(), $this->_matching['module.action'])) {
			$this->makeActive();
      return true;
		}
		
	  $this->_is_parsed = true;
    return false;
	}
	
	/** eof routing **/
	
	/** bof secured **/
	public function requiresAuthentication($boolean = null)
	{
		if (!is_null($boolean))
    {
      $this->_requires_authentication = (bool) $boolean;
    }

		return $this->_requires_authentication;
	}
	
	public function setCredentials()
	{
		$this->requiresAuthentication();
		$args = func_get_args();
		foreach ($args as $arg) {
			if (is_array($arg)) {
				$this->_credentials = $arg; break;
			}
			
			$this->_credentials[] = $arg;
		}
    
    if (count($this->_credentials))
    {
      $this->requiresAuthentication(true);
    }
	}
	
	public function getCredentials()
	{
		return $this->_credentials;
	}
	
	public function checkUserAccess(sfUser $user = null)
  {
    if (!sfContext::hasInstance())
    {
      return true;
    }

    if (is_null($user))
    {
      $user = sfContext::getInstance()->getUser();
    }

    if ($this->requiresAuthentication())
    {
      if (!count($this->getCredentials())) {
        return true;
      }
      
      if (!$user->isAuthenticated()) {
      	return false;
      }
			
			return ($user->hasCredential($this->getCredentials()));
    }
		
		return true;
  }
  /** eof secured **/
  
}
