<?php

/**
 * @TODO
 *  - sa folosesc doctrine collection ca sa simplific cat mai mult lucrurile
 *
 * usage
 * -----
 *  
 */

class vzHashable extends Doctrine_Template
{
    
  protected $_options = array(
                          'mapping_key'   => 'vz_eavs',
                          'eavClass'      => 'EAV',
                          'eavAlias'      => 'EAVS', #entity attributes values
                          
                          'className'     => '%CLASS%EAV',
                          'generateFiles' => false,
                          'table'         => false,
                          'pluginTable'   => false,
                          'children'      => array(),
                        );
                        
  public static 
    $CACHE_PREFIX = 'cache';
                        
  
  public function __construct(array $options = array())
  {
    $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $options);
    $this->_plugin  = new Doctrine_EAV($this->getOptions());
  }
  
  public function setUp()
  {
    $this->_plugin->initialize($this->_table);
    
    $this->hasMany(
      $this->getTable()->getComponentName().'EAV as ' . $this->getOption('eavAlias'),
      array('local' => 'id', 'foreign' => 'entity_id')
    );
    
  }
  
  public function setTableDefinition()
  {
    $this->_table->unshiftFilter(new vzEAVRecordFilter());
    $this->addListener(new Listener_vzHashable($this->_options));
  }
  
  public function hasEav($name)
  {
    foreach ($this->getInvoker()->{$this->_options['eavAlias']} as $attribute)
    {
      if ($attribute->name == $name)
      {
        return true;
      }
    }
    return false;
  }
  
  public function setEav($name, $value, $with_save = false)
  {
    foreach ($this->getInvoker()->{$this->_options['eavAlias']} as $attribute)
    {
      if ($attribute->name == $name)
      {
        $attribute->setValue($value);
        
        if ($with_save)
        {
          $attribute->save();
        }
        return;
      }
    }
    
    $attribute = $this->getEAVTable()->create();
    $attribute->name = $name;
    $attribute->setValue($value);
    
    if ($with_save)
    {
      $attribute->save();
    }
    else
    {
      $this->getInvoker()->{$this->_options['eavAlias']}[] = $attribute;
    }
    
  }
  
  public function store($name, $value, $with_save = false)
  {
    $this->setEav($name, $value, $with_save);
  }
  
  public function setEavs(array $eavs)
  {
    foreach ($eavs as $name => $value)
    {
      $this->setEav($name, $value);
    }
  }
  
  public function getEav($name, $default = null)
  {
    foreach ($this->getInvoker()->{$this->_options['eavAlias']} as $attribute)
    {
      if ($attribute->name == $name)
      {
        return $attribute->getValue();
      }
    }
    
    return $default;
  }
  
  public function retrieve($name, $default = null)
  {
    return $this->getEav($name, $default);
  }
  
  public function getEavsAsArray()
  {
  }
  
  public function removeEav($names)
  {
    if (!is_array($names))
    {
      $names = array($names);
    }
    
    foreach ($this->getInvoker()->{$this->_options['eavAlias']} as $index => $attribute)
    {
      if (in_array($attribute->name, $names))
      {
        unset($this->getInvoker()->{$this->_options['eavAlias']}[$index]);
        
        if ($attribute->exists())
        {
          $attribute->delete();
        }
      }
      
    }
  }
  
  public function saveEavs()
  {
    $this->getInvoker()->{$this->_options['eavAlias']}->save();
  }
  
  protected function loadEavs()
  {
    $attributes = array();
    foreach ($this->getInvoker()->{$this->_options['eavAlias']} as $attribute)
    {
      $attributes[$attribute->name] = $attribute->getValue();
    }
    
    $this->getInvoker()->mapValue($this->_options['mapping_keys']['loaded'], $attributes);
    $this->getInvoker()->mapValue($this->_options['mapping_keys']['current'], $attributes);
  }
  
  protected function getEAVTable()
  {
    return Doctrine::getTable($this->getEAVClass());
  }
  
  protected function getEAVClass()
  {
    return str_replace('%CLASS%', $this->getInvoker()->getTable()->getComponentName(), $this->_options['className']);
  }
  
  public function addEAVQueryTableProxy(Doctrine_Query $query, $alias = '_eavs')
  {
    return $query->leftJoin($query->getRootAlias() . '.EAVS ' . $alias . ' INDEXBY ' . $alias . '.name');
  }
  
  public function retrieveEAVQueryTableProxy($alias = 'a')
  {
    return $this->addEAVQueryTableProxy($this->getInvoker()->getTable()->createQuery($alias));
  }
  
  public function retrieveWithEavsQueryTableProxy(array $eavs, $alias = 'a', $query = null)
  {
    $eav_table = $this->getEAVClass();
    
    if (!$query)
    {
      $query = $this->retrieveEAVQueryTableProxy($alias);
    }
    
    $i = 1;
    foreach ($eavs as $name => $value)
    {
      if (is_int($name))
      {
        $query->andWhere('_eavs.name = ?', $value);
      }
      else
      {
        $value_condition = '';
        $binds = array();
        if (is_array($value))
        {
          $binds = array_merge(array($name), array_map('serialize', $value));
          $value_condition .= '(';
          for ($j = 0; $j < count($value); $j++)
          {
            $value_condition .= " _eavs_$i.value = ? ";
            
            if ($j < count($value) - 1)
            {
              $value_condition .= ' OR';
            }
          }
          $value_condition .= ')';
        }
        else
        {
          $binds = array($name, serialize($value));
          $value_condition = "_eavs_$i.value = ?";
        }
        
        $query->addWhere(
          $alias . ".id in 
            (SELECT _eavs_$i.entity_id FROM $eav_table _eavs_$i WHERE _eavs_$i.name = ? AND " . $value_condition . ")", 
          $binds
        );
        $i++;
      }
    }
    
    return $query;
  }
  
  
  /**** caching ****/
  public function setCache($key, $value, $with_save = false)
  {
    return $this->store(self::$CACHE_PREFIX . '.' . $key, $value, $with_save);
  }
  
  public function getCache($key)
  {
    if ($this->hasCache($key))
    {
      return $this->retrieve(self::$CACHE_PREFIX . '.' . $key);
    }
  }
  
  public function clearCache($key = null)
  {
    if ($key !== null)
    {
      return $this->removeEav(self::$CACHE_PREFIX . '.' . $key);
    }
    
    Doctrine_Core::getTable($this->getEAVClass())->createQuery('eav')->delete()
      ->addWhere('eav.entity_id = ?', $this->getInvoker()->id)
      ->addWhere('eav.name like ?', self::$CACHE_PREFIX . '.%')
      ->execute();
  }
  
  public function hasCache($key)
  {
    return $this->hasEav(self::$CACHE_PREFIX . '.' . $key);
  }
}

class Listener_vzHashable extends Doctrine_Record_Listener
{
  protected $_options = array();

  public function __construct(array $options)
  {
    $this->_options = $options;
  }
  
}

class vzEAVRecordFilter extends Doctrine_Record_Filter_Standard
{
  
  public function init()
  {
    
  }

  public function filterSet(Doctrine_Record $record, $name, $value)
  {
    if (substr($name, 0, 4) == 'eav_')
    {
      return $record->setEav(substr($name, 4), $value);
    }
    else
    {
      return parent::filterSet($record, $name, $value);
    }
  }
  
  public function filterGet(Doctrine_Record $record, $name)
  {
    if (substr($name, 0, 4) == 'eav_')
    {
      return $record->getEav(substr($name, 4));
    }
    else
    {
      return parent::filterGet($record, $name);
    }
  }
}
