<?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_redirect_redirect extends DefaultObject
{
	protected $allowed_keys=array(
		'id', 'pattern', 'link', 'pos', 'active'
	);
	
	public function __construct($id=null)
	{
		if (is_numeric($id)) $this->loadDataById($id);
		elseif($id) $this->loadDataByName($id);
	}

	public function loadDataById($id)
	{
		$data=Db::i()->selectRow("SELECT * FROM ?_redirects WHERE id=?", $id);
		if ($data) {
			$this->set($data);
		}
	}
	
	public function add($data)
	{
		$this->_filterKeys($data);
		$this->id=Db::i()->query("INSERT INTO ?_redirects SET ?a", $data);
		$this->update(array('pos'=>$this->id));
	}
	
	public function delete()
	{
		Db::i()->query("DELETE FROM ?_redirects WHERE id=?", $this->id);
	}
	
	public function toggle()
	{
		$this->update(array('active'=>$this->active?0:1));
	}
	
	public function moveUp()
	{
		$id=Db::i()->selectCell("SELECT id FROM ?_redirects WHERE pos<?d ORDER BY pos DESC LIMIT 1", $this->pos);
		if ($id) $this->_swapSort($id);
	}
	
	public function moveDown()
	{
		$id=Db::i()->selectCell("SELECT id FROM ?_redirects WHERE pos>?d ORDER BY pos LIMIT 1", $this->pos);
		if ($id) $this->_swapSort($id);
	}
	
	protected function _updateDB(&$data)
	{
		return Db::i()->query("UPDATE ?_redirects SET ?a WHERE id=?", $data, $this->id);
	}

	protected function _resetItemCache()
	{
	}
	
	public function getList()
	{
		return Db::i()->select("SELECT id, pattern, link, pos, active FROM ?_redirects ORDER BY pos");
	}
	
	protected function _swapSort($id)
	{
		$redirect=Factory::create('admin_redirect.redirect', $id);
		$old_sort=$this->pos;
		$this->update(array('pos'=>$redirect->pos));
		$redirect->update(array('pos'=>$old_sort));
	}
	
	public function toArray()
	{
		return $this->data;
	}

	public function getEditForm()
	{
		$form = Factory::create('HTML_QuickForm2', '', 'post', array('action'=>''));
		$field1=$form->addElement('fieldset')->setLabel(_m('Правило'));
		
		$pattern=$field1->addElement(
			'text', 'pattern', array('tabindex'=>1, 'id'=>'pattern'),
			array('label' => 'паттерн (поддерживает регулярные выражения)')
		);
		$pattern->addRule('required', 'Паттерн не может быть пустым');
		$link=$field1->addElement('text', 'link', array('tabindex'=>2, 'id'=>'link'), array('label' => 'ссылка'));
		$link->addRule('required', 'Ссылка не может быть пустой');

		$field1->addElement('hidden', 'token', array('value'=>User::i()->token));
		$field1->addElement('submit', '', array('value'=>'Сохранить', 'tabindex'=>3));

		
		if ($this->id) $form->addDataSource(Factory::create('HTML_QuickForm2_DataSource_Array', $this->data));

		return $form;
	}
}