<?php
class MyWeb_File_Controller_Controller extends MyWeb_File_Controller_Abstract
{
	
	
	private $_nameController;
	private $_addContent;
	
	// *** promenne pro metodu methodLogin ***
	protected $_user = NULL;			//user	-	jmeno tridy modelu
	protected $_logout = NULL;		//login	-	jmeno formulare
	protected $_submitLogin = NULL;	//submit_login	-	jmeno tlacitka pro odhlaseni
	protected $_pcontroller = NULL;	//$pcontroller	-	jmeno get parametru
	protected $_paction = NULL;		//$paction	-	jmeno get parametru
	// *** promenne pro metodu methodLogout ***
	protected $_submitLogout = NULL;
	protected $_login = NULL;			//logout	-	jmeno formulare
	
	
	
	public function set_nameController($controller)
	{
		$this->_nameController = $controller;
	}
	
	public function get_nameController()
	{
		return $this->_nameController;
	}
	
	private function createDirectoryView()
	{
		$pathView = $this->_default_path_view_php.$this->_dbTable->get_modelName()."/";
		if (!file_exists($pathView)) {
			mkdir($pathView);
		}
	}
	
	/**
	 * zakladni nastaveni
	 * Enter description here ...
	 */
	private function defaultSettings()
	{
		
		$this->_user = 'user';
		$this->_login = 'login';
		$this->_logout = 'logout';
		$this->_submitLogin = 'submit_login';
		$this->_submitLogout = 'submit_logout';
		$this->_pcontroller = 'pcontroller';
		$this->_paction = 'paction';
		
		
		
		
		
		if (is_null($this->_describeTable)){
			$this->_describeTable = $this->_dbTable->get_describeTable();
		}
		if (is_null($this->_nameController)){
			$this->_nameController = $this->_dbTable->get_modelName();
		}
		$this->createDirectoryView();
	}
	
	
	
	
	public function __construct($dbTable,$path = null)
	{
		$this->_dbTable = $dbTable;
		$this->defaultSettings();
		$this->_path = $path;	//*** pridano zajistuje pouziti nove cesty od uzivatele misto default
		$this->defaultSettingsPath($this->_default_path_controller_php);
		$this->set_typeFile('php');
		$this->_currentPrefix = 6;
		if (0 === strcmp($this->_filename, 'none')){
			$this->_filename = $this->_dbTable->get_modelName();
		}
	}
	
	/**
	 * 
	 * Metoda prida retezec do vysledneho souboru
	 * @param $content
	 */
	public function add_contentFile($content)
	{
		$this->_addContent = $content;
	}
	
	/**
	 * metoda vrati retezec zajistujici autentizaci
	 * Enter description here ...
	 */
	protected function getAuthenticationString($shift = 0)
	{
		$authenticationString = "";
		$delimiter = "\t";
		$resultShift = "";
		
		for ($index = 0; $index < $shift; $index++) {
			$resultShift .= $delimiter;
		}
		$authenticationString .=	$resultShift.'// kontrola opravneni'											. "\n";
        $authenticationString .=	$resultShift.'$authentication = new MyWeb_Controller_Plugin_Authentication();'	. "\n";
        $authenticationString .=	$resultShift.'$authentication->dispatchLoopStartup($this->_request);'			. "\n";
		return $authenticationString;
	}
	
	/*
	**
	 * motodat vytvori retezec pro prevod pole dat nactenych z databaze do 
	 * pole urceneho k naplneni formulare
	 * Enter description here ...
	 * @param $nameSourceArray
	 * @param $nameTargetArray
	 *
	protected function getMoveDataString($nameSourceArray,$nameTargetArray)
	{
		if (is_array($nameSourceArray))
	}*/
	
	public function createContent()
	{
		$nameModel = '$model'.ucfirst($this->_nameController);
		$nameDataController = '$data'.ucfirst($this->_nameController);
		$nameDataControllerForm = '$data'.ucfirst($this->_nameController).'Form';
		$nameDataControllerDb = '$data'.ucfirst($this->_nameController).'Db';
		$namePriKey = current($this->get_dbTables()->get__modelPrimary());
		
		//echo "<p>ddddddddd".current($this->get_dbTables()->get__modelPrimary())."</p>";
		
		$stringFile = "<?php \n";
		//**************************************************************************************
		//**************************************************************************************
			$methodInit = new Zend_CodeGenerator_Php_Method();
			$methodInit	->setName('init');
			$methodInit ->setBody(
									'MyWeb_Log_ApplicationLogger::addLog($this,1,4);' . "\n" .
        							'MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),\''.ucfirst($this->_nameController).'Controller\');'	. "\n\n" .
        							
        							$this->getAuthenticationString()
        						);
        					
			$methodIndex = new Zend_CodeGenerator_Php_Method();
			$methodIndex	->setName('indexAction');
			$methodIndex ->setBody(
									'MyWeb_Log_ApplicationLogger::addLog($this,2,4);' . "\n" .
        							'MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),\''.ucfirst($this->_nameController).'Controller\');' . "\n\n" .
        							
        							$this->getAuthenticationString()
        						);
			
			$methodList = new Zend_CodeGenerator_Php_Method();
			$methodList	->setName('listAction');
			$methodList ->setBody(
							'try {'																		. "\n" .
								"\t".	'MyWeb_Log_ApplicationLogger::addLog($this,3,4);'				. "\n" .
        						"\t".	'MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),\''.ucfirst($this->_nameController).'Controller\');' . "\n\n" .
								
										$this->getAuthenticationString(1)								. "\n" .
								
								"\t".	$nameModel.' = MyWeb_Model_Database::loadModel(\''.ucfirst($this->_nameController).'\');' . "\n\n" .
        						
								"\t".	'$paginator = new MyWeb_Controller_Plugin_Paginator();'			. "\n" .
        						"\t".	'$paginator->setModel('.$nameModel.');'							. "\n" .
        						"\t".	'$paginator->setData($this->getRequest()->getParams());'		. "\n" .
        						"\t".	'$paginator->setRequest($this->getRequest());'					. "\n\n" .
								
								"\t".	'$this->view->select = '.$nameModel.'->createFetchEntrySelect($this->getRequest()->getParams());'	. "\n" .
        						"\t".	'$this->view->pager = $paginator->getPaginator();'													. "\n" .
										
							'}catch (Exception $e){'													. "\n" .
    						"\t".'echo $e->getMessage();'												. "\n" .
							'}'																			. "\n"
        						);
        	
        	
        	$methodList2 = new Zend_CodeGenerator_Php_Method();
			$methodList2	->setName('list2Action');
			$methodList2	->setBody(
								'try {'																		. "\n" .
									"\t".	'MyWeb_Log_ApplicationLogger::addLog($this,3,4);'				. "\n" .
        							"\t".	'MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),\''.ucfirst($this->_nameController).'Controller\');' . "\n\n" .
								
									$this->getAuthenticationString(1)													. "\n" .
			
									"\t".	$nameModel.' = MyWeb_Model_Database::loadModel(\''.ucfirst($this->_nameController).'\');' . "\n" .
        							"\t".	'$form = $model'.ucfirst($this->_nameController).'->getForm(\'search\');'			. "\n\n" .
									
									"\t".	'$paginator = new MyWeb_Controller_Plugin_Paginator();'		. "\n" .
        							"\t".	'$paginator->setModel('.$nameModel.');' 					. "\n" .
									"\t".	'$paginator->setData($this->getRequest()->getParams());'	. "\n" .
									"\t".	'$paginator->setRequest($this->getRequest());' 				. "\n\n" .
								
									"\t".	'//********** Nastaveni javascriptu pro popup window ***********************'. "\n" .
									"\t".	'/*$jsPopupSlave = MyWeb_JavaScript_Popup_Abstract::createJsPopupSlave();'	. "\n" .
									"\t".	'$jsPopupSlave->setIdInput(\'in\');'										. "\n" .
        							"\t".	'$jsPopupSlave->addIdHidden(\'inid\');'										. "\n" .
        							"\t".	'$jsPopupSlave->addIdHidden(\'inid\');'										. "\n" .
        							"\t".	'$jsPopupSlave->addIdHidden(\'inid\');'										. "\n" .
        							"\t".	'$jsPopupSlave->addIdHidden(\'inid\');'										. "\n" .
        							"\t".	'$jsPopupSlave->setIdLink(\'button\');'										. "\n" .
        							"\t".	'$js=$jsPopupSlave->js();'													. "\n\n" .
        
        							"\t".	'$jsPopupSlave->setNameFile(\'slaveList2\');'								. "\n" .
        							"\t".	'//$jsPopupSlave->writeFileJs();*/'											. "\n" .
								
									"\t".	'$this->view->javascriptPopupSlave = $js;'									. "\n" .
        							"\t".	'$this->view->select = '.$nameModel.'->createFetchEntrySelect($this->getRequest()->getParams());'	. "\n" .
        							"\t".	'$this->view->pager = $paginator->getPaginator();'							. "\n" .
    								'}catch (Exception $e){'															. "\n" .
    								"\t".	'echo $e->getMessage();'													. "\n" .
									'}'																					. "\n"
								);
        	
        					
			$methodEdit = new Zend_CodeGenerator_Php_Method();
			$methodEdit	->setName('editAction');
			$methodEdit ->setBody(
								'MyWeb_Log_ApplicationLogger::addLog($this,4,4);'	. "\n" .
        						'MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),\''.ucfirst($this->_nameController).'Controller\');' . "\n" .
								
								$this->getAuthenticationString()					. "\n" .
								
								'$'.$namePriKey.' = $this->getRequest()->getParam(\''.$namePriKey.'\');'. "\n" .
								$nameModel.' = MyWeb_Model_Database::loadModel(\''.ucfirst($this->_nameController).'\');' . "\n" .
        						'$form = '.$nameModel.'->getForm(\'update\');' . "\n" .
								$nameDataController.' = '.$nameModel.'->fetchEntry($id_user);'. "\n\n\n" .
								
								'$'.$namePriKey.'_db = '.$nameDataController.'[\'data\'][\''.$namePriKey.'\'];'. "\n" .
        						'$form->setAction(\'\');'. "\n\n" .
        			
        						'if ($this->getRequest()->isPost() && '										. "\n" .
        							"\t".'((false !== $this->getRequest()->getPost(\'send\',false)) || (false !== $this->getRequest()->getPost(\'delete\',false)))){'. "\n" .
        							"\t".	'if ($form->isValid($this->getRequest()->getPost())){'			. "\n" .
        					
        					
									"\t\t".'if ($this->getRequest()->isPost() && false !== $this->getRequest()->getPost(\'delete\',false)){'. "\n" .
        								"\t\t\t".'// state disabled or enabled'. "\n" .
        								"\t\t\t".$nameModel.'->update('.$nameDataControllerForm.', $'.$namePriKey.'_db);'. "\n" .
        								"\t\t\t".'$this->_redirect(\'/'.$this->_nameController.'/list/\');'. "\n" .
        							"\t\t".'}'. "\n" .
        							"\t\t".'if ($this->getRequest()->isPost() && false !== $this->getRequest()->getPost(\'send\',false)){'. "\n" .
        								"\t\t\t".$nameModel.'->update('.$nameDataControllerForm.', $'.$namePriKey.'_db);'. "\n" .
        								"\t\t\t".'//$this->_redirect(\ '.$namePriKey.'_db);'. "\n" .
        							"\t\t".'}'. "\n" .
        						"\t".'}'. "\n" .
        						"\t".'}else {'. "\n" .
        							"\t\t".'$form->populate('.$nameDataControllerDb.');'. "\n" .
        						"\t".'}'. "\n\n" .
        			
        			
        			
       							'$this->view->jsOpenLinks = $jsOpenLinks;'. "\n" .
        						'$this->view->javascriptPopupMain = $js;'. "\n" .
       							'$this->view->form=$form;'. "\n"
        						);
		
			$methodSearch = new Zend_CodeGenerator_Php_Method();
			$methodSearch	->setName('searchAction');
			$methodSearch	->setBody(
									'MyWeb_Log_ApplicationLogger::addLog($this,5,4);' . "\n" .
        							'MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),\''.ucfirst($this->_nameController).'Controller\');' . "\n\n" .
        							
									$this->getAuthenticationString()					. "\n" .
			
        							$nameModel.' = MyWeb_Model_Database::loadModel(\''.ucfirst($this->_nameController).'\');' . "\n" .
        							'$form = $model'.ucfirst($this->_nameController).'->getForm(\'search\');' . "\n\n" .
									
        							'if ($this->getRequest()->isPost() && (false !== $this->getRequest()->getPost(\'send\',false))){'. "\n" .
        							"\t".	'if ($form->isValid($this->getRequest()->getPost())){'			. "\n" .
        							"\t".	'}'																. "\n" .
        							'}'																		. "\n\n\n" .
        							
        							
        							
        							'//********** Nastaveni javascriptu pro popup window ***********************'. "\n" .
       								'$this->view->jsOpenLinks = $jsOpenLinks;'. "\n" .
        							'$this->view->javascriptPopupMain = $js;'. "\n" .
       								'$this->view->form=$form;'. "\n"
        							);
        					
			$methodNew = new Zend_CodeGenerator_Php_Method();
			$methodNew	->setName('newAction');
			$methodNew ->setBody(
								'MyWeb_Log_ApplicationLogger::addLog($this,6,4);' . "\n" .
        						'MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),\''.ucfirst($this->_nameController).'Controller\');' . "\n\n" .
        						
								$this->getAuthenticationString()					. "\n" .
								
        						$nameModel.' = MyWeb_Model_Database::loadModel(\''.ucfirst($this->_nameController).'\');' . "\n" .
        						'$form = $model'.ucfirst($this->_nameController).'->getForm(\'insert\');' . "\n\n" .
								
        						'if ($this->getRequest()->isPost() && (false !== $this->getRequest()->getPost(\'send\',false))){'. "\n" .
        							"\t".	'if ($form->isValid($this->getRequest()->getPost())){'			. "\n" .
        							"\t\t".		$nameModel.'->insert('.$nameDataControllerForm.');'		. "\n" .
        							"\t\t".		'//$this->_redirect(\ '.$namePriKey.'_db);'	. "\n" .
        							"\t".'}else {'. "\n" .
        							"\t\t".	'$form->populate('.$nameDataControllerForm.');// naplni formular pokud se vyskitla chyba'. "\n" .
        							"\t".'}'								. "\n" .
        							'}'. "\n" .
        							
        							
        							
        							'//********** Nastaveni javascriptu pro popup window ***********************'. "\n" .
       								'$this->view->jsOpenLinks = $jsOpenLinks;'. "\n" .
        							'$this->view->javascriptPopupMain = $js;'. "\n" .
       								'$this->view->form=$form;'. "\n"
        						);
        					
			$class = new Zend_CodeGenerator_Php_Class();
			$class	->setName($this->_dbTable->get_modelName().'Controller extends Zend_Controller_Action')
					->setMethod($methodInit)
					->setMethod($methodIndex)
					->setMethod($methodList)
					->setMethod($methodList2)
					->setMethod($methodEdit)
					->setMethod($methodSearch)
					->setMethod($methodNew);
					
					
					
			if (strcmp($this->_dbTable->get_modelName(),'user') === 0){
				$class	->	setMethod($this->methodLogin())
						->	setMethod($this->methodLogout())
						->	setMethod($this->methodForbidden());
			}
					
					
		
			$stringFile .= $class;
		$this->set_contentFile($stringFile);
	}
	
	
	
	
	/**
	 * metoda vyvori kod akce pr prihlaseni
	 * 
	 */
	protected function methodLogin(){
		
		$methodLogin = new Zend_CodeGenerator_Php_Method();
		$methodLogin	->setName('loginAction');
		$methodLogin ->setBody(
			
						'// inicializuje model																							' . "\n" .
        				'$model'.ucfirst($this->_user).' = MyWeb_Model_Database::loadModel(\''.$this->_user.'\');							' . "\n" .
        				'// inicializuje fotmulare																						' . "\n" .
        				'$form = $model'.ucfirst($this->_user).'->getForm(\''.$this->_login.'\');											' . "\n" .
        				'// otestuje, zda byl odeslan formular																			' . "\n" .
        				'if ($this->getRequest()->isPost() && false !== $this->getRequest()->getPost(\''.$this->_submitLogin.'\', false)) {	' . "\n" .
        	"\t".			'// otestuje korektnost Ä‚ĹźdajÄąĹ»																			' . "\n" .
        	"\t".			'if ($form->isValid($this->getRequest()->getPost())) {														' . "\n" .
        	"\t"."\t".			'$authentication = new MyWeb_Controller_Plugin_Authentication();										' . "\n" .
        	"\t"."\t".			'$authentication->dispatchLoopStartup($this->_request);													' . "\n" .
        	"\t"."\t".			'if ($this->getRequest()->getParam(\''.$this->_pcontroller.'\', false) 										' . "  " .
        	"\t"."\t"."\t".			'&& $this->getRequest()->getParam(\''.$this->_paction.'\', false)){										' . "\n" .
        	"\t"."\t"."\t".			'$this->_redirect(	\'/\'.$this->getRequest()->getParam(\''.$this->_pcontroller.'\').					' . "  " .
        												'\'/\'.$this->getRequest()->getParam(\''.$this->_paction.'\').						' . "  " .
        												'\'/\');																		' . "  " .
        	"\t"."\t".			'}																										' . "\n" .
        	"\t"."\t".			'//$form->getElement(\'user_name\')->addError(\'msg_user_wrong\');										' . "\n" .
        	"\t"."\t".			'//$form->getElement(\'user_password\')->addError(\'msg_user_wrong\');									' . "\n" .
        	"\t".			'}																											' . "\n" .
        				'}																												' . "\n" .
        				'$this->view->form = $form;																						' . "\n"
        				);
        				return $methodLogin;
	}
    	

    /**
     * metoda vytvori kod akce pro odhlaseni logout
     * 
     */
	protected function methodLogout(){
		
		$methodLogout = new Zend_CodeGenerator_Php_Method();
		$methodLogout	->setName('logoutAction');
		$methodLogout ->setBody(
			
						'// inicializuje model																	' . "\n" .
						'$model'.ucfirst($this->_user).' = MyWeb_Model_Database::loadModel(\''.$this->_user.'\');' . "\n" .
						'// inicializuje formulare																' . "\n" .
						'$form = $model'.ucfirst($this->_user).'->getForm(\''.$this->_logout.'\');				' . "\n" .
						'// otestuje, zda byl odeslni formulare													' . "\n" .
						'if ($this->getRequest()->isPost() && 													' . "  " .
		"\t".				'false !== $this->getRequest()->getPost(\''.$this->_submitLogout.'\', false)) {		' . "\n" .
		"\t".					'// odhlaseni uzivatele															' . "\n" .
		"\t".					'Zend_Auth::getInstance()->clearIdentity();										' . "\n" .
		"\t".					'// stranka smeruje na uvodni stranku											' . "\n" .
		"\t".					'$this->_redirect(\'/\');														' . "\n" .
						'}																						' . "\n" .
						'//generovani formulare pohledu															' . "\n" .
						'$this->view->form = $form;																' . "\n"
		);
		return $methodLogout;
	}
    
    
	/**
	 * metoda vytvori kod akce forbidden
	 * 
	 */
	protected function methodForbidden(){
		
		$methodForbidden = new Zend_CodeGenerator_Php_Method();
		$methodForbidden	->setName('forbiddenAction');
		$methodForbidden	->setBody(" ");
		
		return $methodForbidden;
	}
	
}