<?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 admin_tree_mapper
{
	protected $allowedKeys=array(
		'tree_id', 'parent_id', 'symlink', 'name', 'params', 'template', 'menu', 'sitemap',
		'path', 'pos', 'lang_id', 'show', 'external', 'module'
	);
	
	public function getNodesByArrayId($id)
	{
		$result=Db::i()->select("SELECT * FROM ?_tree WHERE tree_id IN (?a) ORDER BY FIELD(treE_id, ?a)", $id, $id);
		
		$data=array();
		if ($result) {
			foreach ($result as $item) {
				$obj=Factory::create('admin_tree.node_entity', $item);
				$data[$obj->id]=$obj;
			}
		}
		return $data;
	}
	
	public function updateNode($node)
	{
		$data=$node->getFilteredKeys($this->allowedKeys);
		
		if (isset($data['module'])) {
			$modules=$data['module'];
			unset($data['module']);
			$modules=(is_array($modules))?array_keys($modules):array();
			$this->_setModules($node->id, $modules);
		}
		return Db::i()->query("UPDATE ?_tree SET ?a WHERE tree_id=?", $data, $node->id);
	}
	
	public function addNode($node)
	{
		$data=$node->getFilteredKeys($this->allowedKeys);
		$modules=$data['module'];
		unset($data['module']);
		$id=Db::i()->query("INSERT INTO ?_tree (?#) VALUES(?a)", array_keys($data), array_values($data));
		$modules=(is_array($modules))?array_keys($modules):array();
		$this->_setModules($id, $modules);
		return $id;
	}
	
	protected function _setModules($id, $modules=array())
	{
		Db::i()->query("DELETE FROM ?_includes WHERE tree_id=?", $id);
		if (count($modules)) {
			foreach ($modules as $val) {
				Db::i()->query("INSERT INTO ?_includes (tree_id, module_id) VALUES(?, ?)", $id, $val);
			}
		}
	}
	
	public function deleteNodes($ids)
	{
		Db::i()->query("DELETE FROM ?_includes WHERE tree_id IN (?a)", $ids);
		Db::i()->query("DELETE FROM ?_tree WHERE tree_id IN (?a)", $ids);
	}
	
	public function getIdsByParentId($id)
	{
		return Db::i()->selectCol("SELECT tree_id FROM ?_tree WHERE parent_id=? ORDER BY pos", $id);
	}
	
	public function getAllNodesId()
	{
		return Db::i()->selectCol("SELECT tree_id FROM ?_tree");
	}
	
}