<?php
//include_once 'MDB2.php';
/**
* trida MyWeb_DbTable_DbTable_DbTable získává a ukládá informace o databázové tabulce
* získané informace uloží do souboru.php
*/
class MyWeb_DbTable_DbTable extends MyWeb_plugin
{
	/*
	 * chybi trida pro vyjimky ve vsech metodach
	 */
	private $_db;
	private $_describeTable = array('0'=>NULL);
	
	//udaje modelu
	private $_modelName;					//jmeno tabulky
	private $_modelPrimary;					//jmeno primarniho klice
	private $_modelReferenceMap;			//pole s propojenim tabulek
	
	private $_modelRefTableClass;			//jmeno tridy modelu s cizi tabulkou
	private $_modelColumns;					//jmeno sloupce s cizim klicem
	private $_modelrefColumns;				//jmeno primarniho klice v cizi tabulce
	
	 /*****************************************************************************
	  * 	set and get methods for variables
	  *****************************************************************************/
	
	public function set_describeTable($value)
	 {
	 	$this->_describeTable = $value;
	 }
	 public function get_describeTable()
	 {
	 	return $this->_describeTable;
	 }
	
	 public function set_modelName($value)
	 {
	 	$this->_modelName = $value;
	 }
	 public function get_modelName()
	 {
	 	return $this->_modelName;
	 }
	 
	 public function set__modelPrimary($value)
	 {
	 	$this->__modelPrimary = $value;
	 }
	 public function get__modelPrimary()
	 {
	 	return $this->_modelPrimary;
	 }
	 
	 public function set_modelReferenceMap($value)
	 {
	 	$this->_modelReferenceMap = $value;
	 }
	 public function get_modelReferenceMap()
	 {
	 	return $this->_modelReferenceMap;
	 }
	 
	 public function set_modelRefTableClass($value)
	 {
	 	$this->_modelRefTableClass = $value;
	 }
	 public function get_modelRefTableClass()
	 {
	 	return $this->_modelRefTableClass;
	 }
	 
	 public function set_modelColumns($value)
	 {
	 	$this->_modelColumns = $value;
	 }
	 public function get_modelColumns()
	 {
	 	return $this->_modelColumns;
	 }
	 
	 public function set_modelrefColumns($value)
	 {
	 	$this->_modelrefColumns = $value;
	 }
	 public function get_modelrefColumns()
	 {
	 	return $this->_modelrefColumns;
	 }
	 
	 public function set_db($value)
	 {
	 	$this->_db = $value;
	 }
	 public function get_db()
	 {
	 	return $this->_db;
	 }
	 
	 
	 
	 
	 
	 /**
	  * metoda zajisti ze tabulka napr article_has_subject
	  * bude vystupovat jako tabulka articleHasSubject
	  * 
	  */
	 private function tableHas(){
	 	$pos = strpos($this->_modelName, '_has_');
		if ($pos !== false){
			$stringArray = explode('_', $this->_modelName);
			$stringArray[1] = ucfirst($stringArray[1]);
			$stringArray[2] = ucfirst($stringArray[2]);
			$this->_modelName = ucfirst(implode('', $stringArray));
		}
	 }
	 
	 
	 //14
	/**
	 * 
	 *  trida auto model bude obsahovat objekty popisujici jednotlive tabulky
	 *  
	 *  @param string $table Seznam jmen databázových tabulek
	 *  @param Zend_Db_Adapter $db Přístupové informace k databázi (phptype,username,password...)
	 *  @return Zend_Form
	 */
	
	public function __construct($table,$db)
	{
		$this->addLog($this,15,4);
        $this->showMe($this->showLog()."",'MyWeb_DbTable_DbTable_DbTable');
        
		$this->_modelName=$table;//ucwords() prvni pismeno velke
		$this->_db=$db;
		
		$this->describeTable();
		$this->identificationRows();
		$this->tableHas();
	}
	
	public function loadTable($table,$db)
	{
		$this->addLog($this,2,4);
        $this->showMe($this->showLog()."",'MyWeb_DbTable_DbTable_DbTable');
        
		$this->_modelName=$table;
		$this->_db=$db;
		
		$this->describeTable();
		$this->identificationRows();
	}
	
	
	
	/**
	 * Vytváří databázové dotazy "describe jméno_tabulky",
	 * Výsledky dotazů ukládá do $this->_describeTable[1..počet sloupců tabulky]=array(sloupce výsledku dotazu)
	 * 
	 * protected $_describeTableRow=array(
									'Field'		=>NULL,
									'Type'		=>NULL,
									'Null'		=>NULL,
									'Key'		=>NULL,
									'Default'	=>NULL,
									'Extra'		=>NULL);
	 */
	
	private function describeTable()
	{
		$this->addLog($this,18,4);
        $this->showMe($this->showLog()."",'MyWeb_DbTable_DbTable_DbTable');
        
		$query="describe ".$this->_modelName;
		//echo "<p>".$query."</p>";
		$result = $this->_db->query($query);
		$tableColumn=0;
		
		// columen name DESCRIBE: Field, Type, Null, Key, Default, Extra
		
		//je nutne data prevest takto z $result protoze jinak zaniknou
		foreach ($result as $key1 => $value1){
			foreach ($value1 as $key2 => $value2){
				$this->_describeTable[$key1]=array(
				'Field'		=>$value1['Field'],			
				'Type'		=>$value1['Type'],
				'Null'		=>$value1['Null'],
				'Key'		=>$value1['Key'],
				'Default'	=>$value1['Default'],
				'Extra'		=>$value1['Extra']
				);
			}
		}
	}
	
	
	/**
	 * Rozpozná primání a sekundární klíče z $this->_describeTable a roztřídí je do polí
	 */
	private function identificationRows()
	{
		$this->addLog($this,4,4);
        $this->showMe($this->showLog()."",'MyWeb_SourceFileCreator_DbTable_DbTable');
        
		$columnTable=0;
		$countFk=0;
		$countPk=0;
		for ($columnTable=0; $columnTable < count($this->_describeTable); $columnTable++)
		{
			
			//********************* PRIMARY KEY ******************
			if ($this->_describeTable[$columnTable]['Key']=='PRI')
			{
				$this->_modelPrimary[$countPk]=$this->_describeTable[$columnTable]['Field'];
				$countPk++;
			}
			//*************** FOREIGEN KEY ********************
			if ($this->_describeTable[$columnTable]['Key']=='MUL')
			{
				$this->_modelColumns=$this->_describeTable[$columnTable]['Field'];
				$implodeArray = explode("_", $this->_describeTable[$columnTable]['Field']);
				$this->_modelRefTableClass[$countFk]=$implodeArray[0];
				$this->_modelrefColumns[]=$implodeArray[1]."_".$implodeArray[2];
					
				$this->_modelReferenceMap[$this->_modelRefTableClass[$countFk]]=array
				(
							'columns'	=>	$this->_modelColumns,
							'refTableClass'	=>	$this->_modelRefTableClass[$countFk],
							'refColumns'	=>	current($this->_modelrefColumns)
				);
				current($this->_modelrefColumns);
				$countFk++;			
			}
		}
		
		if ($countPk > 1){
			$countk = $countFk;
			foreach ($this->_describeTable as $key => $value) {
					echo "<p>"."describe"." ".$this->_describeTable[$key]['Field']."</p>";
					if (in_array($this->_describeTable[$key]['Field'],$this->_modelPrimary)){
						$this->_modelColumns=$this->_describeTable[$key]['Field'];
						$implodeArray = explode("_", $this->_describeTable[$key]['Field']);
						$this->_modelRefTableClass[$countk]=$implodeArray[0];
						$this->_modelrefColumns[]=$implodeArray[1]."_".$implodeArray[2];
						
						$this->_modelReferenceMap[$this->_modelRefTableClass[$countk]]=array
						(
							'columns'	=>	$this->_modelColumns,
							'refTableClass'	=>	$this->_modelRefTableClass[$countk],
							'refColumns'	=>	current($this->_modelrefColumns)
						);
						next($this->_modelrefColumns);
						$countk++;
					}
			}
		}
	}
	
	
	public function validation_tables($tables)
	{
		$this->addLog($this,6,4);
        $this->showMe($this->showLog()."",'MyWeb_SourceFileCreator_AutoCreator');
        
		// Musim dodelat kontrolu vstupnich udaji
		/*
		 * jmeno tabulky
		 * kontrola dsn
		 * 
		 */
		
		// validace vstupnich tabulek
		$query="show TABLES from ".$this->_dsn['database'];
		$response = $this->_db->query($query);
		$indexArray=0;
		while ($row = $response->fetchRow()) {
			$poleJmenTabulek[$indexArray++]=$row[0];					//vytvorim pole s nazvi vsech tabulek
		}
		if ((count($tables)==1) && ($tables[0]=="all"))
		{
			foreach ($poleJmenTabulek as $key => $val) 					//kopirovani pole
			{
    			$this->_table[$key]=$poleJmenTabulek[$key];
			}
			return true;
		}else {
			$indexArray=0;
			while ($indexArray<count($tables))
			{
				if (in_array($tables[$indexArray],$poleJmenTabulek))		//v ciklu peohledavam pole vsech tabulek
				{
					$indexArray++;
					if ($indexArray==count($tables))
					{
						return true;
					}
				}else {
					echo "table $tables[$indexArray] neni v databazi\n";
					return false;
				}
			}
		}
	}
	
	
	public function validation_adatpteru($dsn)
	{
		$this->addLog($this,3,4);
        $this->showMe($this->showLog()."",'MyWeb_SourceFileCreator_AutoCreator');
											//***dodelat validaci
											//***dodelat trida na vyjimky
		
		if ($dsn=="undefined")
		{
			$this->_dsn=$this->_defaultDsn;
		}else {
			$this->_dsn=$dsn;
		}
	}
}