<?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 news_mapper
{
	protected $allowedKeys=array('date', 'title', 'text', 'lang_id');

	public function getNewsByFilter($filter, $order, &$count, $perPage=10, $page=1)
	{
		if (empty($filter['lang_id'])) $filter['lang_id']=false;
		if (empty($filter['ignore_date'])) $filter['ignore_date']=false;
		$_order=$this->_buildOrderString($order);
		
		$result=Db::i()->selectPage(
			$count,
			"SELECT new_id FROM ?_news
			WHERE
			1=1
			{AND lang_id=?}
			{AND `date`<?d}
			ORDER BY {$_order}
			LIMIT ?d, ?d",
			$filter['lang_id']?$filter['lang_id']:DBSIMPLE_SKIP,
			$filter['ignore_date']?DBSIMPLE_SKIP:time(),
			($page-1)*$perPage, $perPage
		);
		$data=array();	
		if ($result) {
			foreach ($result as $item) {
				$data[]=$item['new_id'];
			}
		}
		return $data;
	}
	
	public function getNewsByArrayId($id)
	{
		$result=Db::i()->select(
			"SELECT *
			FROM ?_news
			WHERE new_id IN(?a)
			ORDER BY FIELD(new_id, ?a)",
			$id, $id
		);

		$data=array();
		if ($result) {
			foreach ($result as $item) {
				$obj=Factory::create('news.entity', $item);
				$data[$obj->id]=$obj;
			}
		}
		return $data;
	}
	
	protected function _buildOrderString($order)
	{
		$possibleOrders = array('new_id', 'date', 'title', 'lang_id');
		$_order = '';
		foreach ($order as $key => $value) {
			if (!in_array($key, $possibleOrders)) {
				unset($order[$key]);
			} elseif (in_array($value, array('asc', 'desc'))) {
				$_order .= " `{$key}` {$value},";
			}
		}
		$_order = trim($_order, ',');
		if ($_order == '') $_order = ' `date` desc, new_id desc ';
		return $_order;
	}
	
	public function addNew($new)
	{
		$data=$new->getFilteredKeys($this->allowedKeys);
		return Db::i()->query(
			"INSERT INTO ?_news (?#) VALUES(?a)", array_keys($data), array_values($data)
		);
	}
	
	public function updateNew($new)
	{
		$data=$new->getFilteredKeys($this->allowedKeys);
		return Db::i()->query("UPDATE ?_news SET ?a WHERE new_id=?", $data, $new->id);
	}
	
	public function deleteNew($new)
	{
		return Db::i()->query("DELETE FROM ?_news WHERE new_id=?", $new->id);
	}
	
}