<?php
/**
 * @link http://svn.doctrine-project.org/extensions/Taggable/branches/1.2-1.0/lib/Doctrine/
 */
class Core_Doctrine_Template_Attributable extends Doctrine_Template
{
    protected $_options = array(
        'attributeName'         => 'Attribute',
        'attributeValueName'    => 'AttributeValue',
        'generateFiles'         => true,
    );

    /**
     *
     * @var Core_Doctrine_Record_Attribute
     */
    protected $_plugin;

    public function __construct(array $options = array())
    {
        parent::__construct($options);
        $this->_plugin = new Core_Doctrine_Record_Attribute($this->_options);
    }

    public function setUp()
    {
        $this->_plugin->initialize($this->_table);
    }

    /**
     * Add attribute
     *
     * @param Attribute $attribute
     * @param AttributeValue $attributeValue
     *
     * @return Doctrine_Record
     */
    public function addAttribute(Attribute $attribute, AttributeValue $attributeValue = null)
    {
        return $this->_plugin->addAttribute($this->getInvoker(), $attribute, $attributeValue);
    }

    /**
     * Remove attribute
     *
     * @param Attribute $attribute
     * @param AttributeValue $attributeValue
     *
     * @return Doctrine_Record
     */
    public function removeAttribute(Attribute $attribute, AttributeValue $attributeValue = null)
    {
        return $this->_plugin->removeAttribute($this->getInvoker(), $attribute, $attributeValue);
    }

    /**
     * Get all attributes
     *
     * @return array
     */
    public function getAttributes()
    {
        return $this->getInvoker()->get('Attributes');
    }

    public function getRelatedByAttributes()
    {
        $entity         = $this->getInvoker();
        $attributes     = $entity->getAttributes();

        if ($attributes->count() == 0) {
            return array();
        }

        $values = array();
        $query = $entity->getTable()->createQuery('a')
                ->select('a.*, COUNT(*) as cnt')
                ->innerJoin('a.Attributes as attrs')
                ->where('a.id != ?')
                ->groupBy('a.id')
                ->orderBy('cnt DESC');

        $values[]   = $entity->id;
        $orWhere    = array();
        foreach ($attributes as $relatedAttribute) {
            $orWhere[]  = 'attrs.attribute_id = ? AND attrs.attribute_value_id = ?';
            $values[]   = $relatedAttribute->attribute_id;
            $values[]   = $relatedAttribute->attribute_value_id;
        }

        if (!empty($orWhere)) {
            $query->andWhere(implode(' OR ', $orWhere));
        } else {
            return array();
        }

        return $query->execute($values);
    }
}