<?php

/**
* 
*/
class guest_post extends DefaultObject
{
	protected $cache_key='guest_post_';

	protected $mapper=null;
	
	public $validation=HTML_QuickForm2_Rule::ONBLUR_CLIENT_SERVER;
	
	public function __construct($mapper=null)
	{
		if (is_object($mapper)) {
			$this->mapper=$mapper;
		} else {
			$this->mapper=Factory::create('guest.mapper');
		}
		Factory::load('guest.post_entity');
	}
	
	public function getPostsbyPage($perPage=10, $page=1)
	{
		$page=(intval($page)<=0)?1:intval($page);
		
		$data=array();
		
		$cache_key='guest_'.$perPage.'_'.$page;

		if (false === ($data=TCache::get($cache_key))) {
			$data = array(
				'collection'=>$this->mapper->getPosts($count, $perPage, $page),
				'count'=>$count
			);
			TCache::set($data, $cache_key, array('guest_update'), 60*60*24*7);
		}
		$data['collection'] = $this->getPostsByArrayId($data['collection']);
		return $data;
	}
	
	public function getPostEntity()
	{
		return Factory::create('guest.post_entity');
	}

	public function getPostById($id)
	{
		if (!is_numeric($id)) return null;

		$post = $this->getPostsByArrayId(array($id));

		if (isset($post[$id])) {
			return $post[$id];
		}
		return null;
	}
	
	public function getPostsByArrayId($id)
	{
		if ($data=$this->_getItemsByArrayId($id)) {
			$users=array();
			foreach ($data as $post) {
				if ($post->user_id) $users[]=$post->user_id;
			}
			
			$users=User::i()->getUsersByIds($users);
			
			foreach ($data as $post) {
				$post->msg_html=getbb($post->msg);
				if ($post->answer) $post->answer_html=getbb($post->answer);

				if ($post->user_id && array_key_exists($post->user_id, $users)) $post->user=$users[$post->user_id];
				else {
					$post->user=User::getUser();
					$post->user->login=$post->name;
					$post->user->email=$post->email;
				}
			}
		}
		return $data;
	}
	
	protected function _getItemsByArrayIdFromStorage($id)
	{
		return $this->mapper->getPostsByArrayId($id);
	}
	
	public function add($post)
	{
		TCache::clean('MATCH_TAG', array($this->_getCacheKeyCommon()));
		return $post->id=$this->mapper->addPost($post);
	}
	
	public function delete($post)
	{
		TCache::clean('MATCH_TAG', array($this->_getCacheKeyCommon()));
		TCache::remove($this->_getCacheKey().$post->id);
		return $this->mapper->deletePost($post);
	}
	
	public function update($post)
	{
		TCache::clean('MATCH_TAG', array($this->_getCacheKeyCommon()));
		TCache::remove($this->_getCacheKey().$post->id);
		return $this->mapper->updatePost($post);
	}
	
	public function buildEditForm($post=null)
	{
		$form = Factory::create('HTML_QuickForm2', 'guest_form', 'post', array('action'=>''));
		$form->addElement('hidden', 'token', array('value' => User::i()->token));
		
		if ($post) {
			$form->addDataSource(
				Factory::create(
					'HTML_QuickForm2_DataSource_Array', 
					array(
						'name'=>$post->user->login,
						'email'=>$post->user->email,
						'msg'=>$post->msg,
						'answer'=>$post->answer
					)
				)
			);
		}
		
		if (User::i()->isGuest()) {
			$login=$form->addElement('text', 'name', null, array('label' => 'Имя:'));
			$email=$form->addElement('text', 'email', null, array('label' => 'Email:'));
			$login	->addRule('required', 'Вы не ввели имя')
					->and_(
						$login->createRule(
							'callback', 'Такой пользователь уже зарегистрирован',
							array('callback'=>array($this, 'IsLoginNotExists'),	'arguments'=>array(false))
						)
					);
		} elseif (is_object($post)) { //если редактируем сообщение
			if (!$post->user_id) {
				$login=$form->addElement('text', 'name', null, array('label' => 'Имя:'));
				$login	->addRule('required', 'Вы не ввели имя')
					->and_(
						$login->createRule(
							'callback', 'Такой пользователь уже зарегистрирован',
							array('callback'=>array($this, 'IsLoginNotExists'),	'arguments'=>array(false))
						)
					);
				$email=$form->addElement('text', 'email', null, array('label' => 'Email:'));	
			}
		}
		
		$msg = $form->addElement(
			'textarea', 'msg',
			array('cols' => 50, 'rows' => 7, 'id'=>'msg', 'class'=>'bbcode'),
			array('label' => 'Сообщение:')
		);
		$msg->addRule('required', 'Вы не ввели сообщение');
		
		if ($post) {
			//если сообщение редактируется - выводми форму ответа
			$answer = $form->addElement(
				'textarea', 'answer', array('cols' => 50, 'rows' => 7, 'id'=>'answer', 'class'=>'bbcode'),
				array('label' => 'Ответ:')
			);
		}
		$form->addElement('submit', 'submit', array('value' => 'Отправить'));
		
		if (!empty($answer)) {
			$answer->setAttribute('autofocus');
		} elseif (!empty($login)) {
			$login->setAttribute('autofocus');
		} else {
			$msg->setAttribute('autofocus');
		}
		
		return $form;
	}
	
	public function IsLoginNotExists($login)
	{
		return (User::i()->IsLoginExists($login))?false:true;
	}
}