<?php
/**
 * Category model.
 *
 * @package koubel homepage
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */

/**
 * Category model class
 *
 * @package koubel homepage
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */
class Blog_Model_Category extends Blog_Model_Model
{
    /**
     * category id
     * @var int
     */
    private $_id;

    /**
     * category name
     * @var string
     */
    private $_name;

    /**
     * title url for the category
     * @var string
     */
    private $_titleUrl;

    /**
     * count of articles for the category
     * @var int
     */
    private $_articleCount;

    /**
     *
     * @var Zend_Paginator
     */
    private $_articlePaginator;
    
    protected function _setDefaultDao()
    {
        $this->setDao(new Blog_Model_Dao_Category());
    }

    public function getId()
    {
        return $this->_id;
    }

    public function setId($id)
    {
        $this->_id=$id;
    }

    public function getName()
    {
        return $this->_name;
    }

    public function setName($name)
    {
        $this->_name=$name;
    }

    public function getTitleUrl()
    {
        return $this->_titleUrl;
    }

    public function setTitleUrl($str)
    {
        $this->_titleUrl=$str;
    }

    /**
     * Gets count of articles for the current category
     * @return int
     */
    public function getArticleCount()
    {
        if (!isset($this->_articleCount)) {
            $categoryArticlesRel = new Blog_Model_Dao_CategoryArticle();
            $this->_articleCount = $categoryArticlesRel->getArticleCount($this->_id);
        }

        return $this->_articleCount;
    }

    public function getAll($pageNo=null,$perPageItems=null,$extendedInfo=null)
    {
        $rows=$this->getDao()->fetchAllItems($pageNo,$perPageItems,$extendedInfo);

        return $this->_getSet($rows);
    }

    protected function _setPropFromArray(&$arr)
    {
        foreach($arr as $key=>$val) {
            $this->{"_".$key}=$val;
        }
    }

    public function getByArticle(Blog_Model_Article $article)
    {
        $currentArticle = $article->getDaoRow();
        $articleCategories = $currentArticle->findManyToManyRowset(
            'Blog_Model_Dao_Category', 'Blog_Model_Dao_CategoryArticle');

        return $this->_getSet($articleCategories);
    }

    public function getArticles($pageNo=null,$perPageItems=null)
    {
        $article = new Blog_Model_Article();
        return $article->getByCategory($this,$pageNo,$perPageItems);
    }

    /**
     * Sets paginator for articles in current category
     * @param Zend_Paginator $paginator
     */
    public function setArticlePaginator(Zend_Paginator $paginator) {
        $this->_articlePaginator = $paginator;
    }

    /**
     * Gets paginator for articles in current category
     * @return Zend_Paginator
     */
    public function getArticlePaginator() {
        return $this->_articlePaginator;
    }
    
    public function findByTitleUrl($titleUrl)
    {
        $row=$this->getDao()->findByTitleUrl($titleUrl);

        if (is_null($row)) {
            return false;
        } else {
            $this->_setFromDaoRow($row->toArray());
            return true;
        }
    }

    public function findById($id)
    {
        $row=$this->getDao()->find($id)->current();
        $this->_setFromDaoRow($row->toArray());
    }

    public function findByArrId($ids)
    {
        $rows=$this->getDao()->find($ids);
        return $this->_getSet($rows);
    }

    protected function _inflectDaoRowIndexes(&$arr)
    {
        $notAllowedIndexes=array("dao");

        $keys=array_keys($arr);
        foreach($keys as $key) {
            //unset not allowed indexes
            if (in_array($key,$notAllowedIndexes))
                throw new Exception("you cannot use $key index as the column index");

            switch ($key) {
            case "titleURL":
                MKLib_Utils::renameKey($arr,$key,"titleUrl");
                break;
            default:
                break;
            }
        }
    }

    /**
     * Gets database row object which corresponds our current properties.
     * It is used mostly for the operation with the relationship. Hence we need
     * to set only keys
     * @param bool $keyOnly true - sets only key properties (primary and foreign) it is
     * enough in most situations, false - sets all properties
     * @return Zend_Db_Table_Row_Abstract
     */
    public function getDaoRow($keyOnly=true)
    {
        $data = array(
            "id"=>$this->_id
        );

        if (!$keyOnly) {
            $data["name"]=$this->_name;
            $data["titleURL"]=$this->_titleUrl;
        }

        $row=$this->getDao()->createRow($data);
        return $row;
    }

    public function insert()
    {
        $this->_id=$this->getDao()->insert(
            array("name"=>$this->_name,
            "titleURL"=>$this->_titleUrl
        )
    );
    }

    public function update()
    {
        $this->getDao()->update(
            array(
                "name"=>$this->_name,
                "titleUrl"=>$this->_titleUrl,
            ), "id=$this->_id"
        );
    }

    public function delete()
    {
        $this->getDao()->delete("id=$this->_id");
    }

    /**
     * Update articles for the current category.
     * @param array $newArticlesIds array with new set of article Ids
     * @throws new Zend_Db_Exception when some database operation fails
     */
    public function updateArticles($newArticlesIds)
    {
        $currentCategoryRow = $this->getDaoRow();

        //get current category article IDs
        $currentCategoryArticles = $currentCategoryRow->findManyToManyRowset(
            'Blog_Model_Dao_Article', 'Blog_Model_Dao_CategoryArticle');
        $currentIds=array();
        foreach($currentCategoryArticles as $article) {
            $currentIds[]=$article->id;
        }

        $categoryArticleDao = new Blog_Model_Dao_CategoryArticle();

        //new articles
        $diff=array_diff($newArticlesIds,$currentIds);
        foreach($diff as $articleId) {
            $categoryArticleDao->insert(
                array("category_id"=>$this->_id,"article_id"=>$articleId)
            );
        }

        //old articles - articles which were assigned and now aren't, these
        //will be removed
        $diff = array_diff($currentIds,$newArticlesIds);
        foreach($diff as $articleId) {
            $categoryArticleDao->delete("category_id = $this->_id AND article_id=$articleId");
        }
    }
}
