<?php

class Definition extends PhpObject {
	
	const DEF_TABLE = 'definitions';
	
	/**
	 * DB
	 * @var Db
	 */
	private $oDb;
	private $iDefId;
	private $iUserId;
	
	public function __construct(Db &$oDb, $iUserId=0, $iDefId=0)
	{
		parent::__construct(__CLASS__, Settings::DEBUG);
		$this->oDb = &$oDb;
		$this->setUserId($iUserId);
		$this->setDefId($iDefId);
	}
	
	public function setUserId($iUserId) {
		$this->iUserId = $iUserId;
	}
	
	public function setDefId($iDefId) {
		$this->iDefId = $iDefId;
	}
	
	public function getDefinitions($iDefId=0) {
		$asConstraints = array(Db::getId(Auth::USER_TABLE)=>$this->iUserId);
		if($iDefId > 0) $asConstraints[Db::getId(self::DEF_TABLE)] = $iDefId;
		
		$asDefs = $this->oDb->selectRows(array('from'=>self::DEF_TABLE, 'constraint'=>$asConstraints), Db::getId(self::DEF_TABLE));
		return $asDefs;
	}
	
	public function getDefinition() {
		$asDef = array();
		if($this->iDefId > 0) {
			$asDef = $this->getDefinitions($this->iDefId);
			if(!empty($asDef)) $asDef = array_shift($asDef);
		}
		return $asDef;
	}
	
	public function setDefinition($sTitle, $sDesc) {
		$asInfo = array(Db::getId(Auth::USER_TABLE)=>$this->iUserId, 'title'=>$sTitle, 'description'=>$sDesc);
		if($this->iDefId == 0) {
			$iDefId = $this->oDb->insertRow(self::DEF_TABLE, $asInfo);
		}
		else {
			$iDefId = $this->oDb->updateRow(self::DEF_TABLE, $this->iDefId, $asInfo);
		}
		$this->setDefId($iDefId);
		return ($iDefId > 0);
	}
}