<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class bug_tracker_item extends DefaultObject
{
	protected $cache_key='bt_item_';

	public function __construct($mapper=null)
	{
		if (is_object($mapper)) {
			$this->mapper=$mapper;
		} else {
			$this->mapper=Factory::create('bug_tracker.mapper');
		}
		Factory::load('bug_tracker.item_entity');
	}

	public function add($item)
	{
		TCache::clean('MATCH_TAG', array($this->_getCacheKeyCommon()));
		return $this->mapper->addItem($item);
	}

	public function update($item)
	{
		TCache::remove($this->_getCacheKey().$item->id);
		TCache::clean('MATCH_TAG', array($this->_getCacheKeyCommon()));
		return $this->mapper->updateItem($item);
	}
	
	public function delete($item)
	{
		TCache::remove($this->_getCacheKey().$item->id);
		TCache::clean('MATCH_TAG', array($this->_getCacheKeyCommon()));
		return $this->mapper->deleteItem($item);
	}

	public function getItemsByFilter($filter=array(), $page=1, $atPage=10)
	{
		$page=(intval($page)<=0)?1:intval($page);

		$key='bug_tracker_items_filter_'.md5(serialize($filter).$page.$atPage);
		if (false === ($data=TCache::get($key))) {
			$data = array(
				'collection'=>$this->mapper->getItemsByFilter($count, $filter, $page, $atPage),
				'count'=>$count
			);
			TCache::set($data, $key, array($this->_getCacheKeyCommon()));
		}
		$data['collection'] = $this->getItemsByArrayId($data['collection']);

		return $data;
	}

	public function getById($id)
	{
		$data=$this->getItemsByArrayId(array($id));
		if (isset($data[$id])) {
			return $data[$id];
		}
		return null;
	}


	public function getItemsByArrayId($id)
	{
		if ($data=$this->_getItemsByArrayId($id)) {
			$users=$versions=array();
			foreach ($data as $item) {
				$users=array_merge(
					$users,
					array($item->author_id, $item->approver_id, $item->performer_id)
				);
				$versions[]=$item->version_id;
			}

			$users=User::i()->getUsersByIds($users);
			
			$versions=$this->_getVersion()->getVersionsByArrayId($versions);
			
			foreach ($data as $item) {
				$item->author=$this->getUserObj($item->author_id, $users);
				$item->approver=$this->getUserObj($item->approver_id, $users);
				$item->performer=$this->getUserObj($item->performer_id, $users);
				$item->version=$versions[$item->version_id];
			}
		}
		return $data;
	}

	public function _getItemsByArrayIdFromStorage($id)
	{
		return $this->mapper->getItemsByArrayId($id);
	}
	
	public function updateLastPost($item)
	{
		$this->mapper->setItemLastUpdate($item);
		$this->update($item);
	}
	
	protected function _getVersion()
	{
		return Factory::create('bug_tracker.version');
	}
}