<?php
/**
 * Validator which checks if the file does not exist id database
 *
 * @category  MyWeb
 * @package   MyWeb_Validate
 * @copyright 
 * @license   
 */
class MyWeb_Validate_IsExistDbValue extends Zend_Validate_Abstract
{
    /**
     * @const string Error constants
     */
    const DOES_EXISTDB = 'fileNotExistsDbDoesExist';
    const DOES_ENTRYEXISTDB = 'entryNotExistsDbDoesExist';
    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::DOES_EXISTDB => "File '%value%' exists in dB",
        self::DOES_ENTRYEXISTDB => "Entry '%value%' not exists in dB",
    );
    
    /**
     * Column table
     *
     * @var string
     */
    protected $_column;
    
	/**
     * Column table
     *
     * @var string
     */
    protected $_foreignTable = array('foreign' => FALSE,'validate' => FALSE);

    /**
     * Primary key row
     *
     *
     * @var integer
     */
    protected $_id;
    
    /**
     * Databese storage
     *
     *
     * @var 
     */
    protected $_model;
	
 	public function __construct($options = array())
    {
    	if (!is_array($options)) {
            $options     = func_get_args();
            $temp['column'] = array_shift($options);
            if (!empty($options)) {
                $temp['id'] = array_shift($options);
            }
    		if (!empty($options)) {
                $temp['storage'] = array_shift($options);
            }
            $options = $temp;
        }
        
        
        
        
        /****************************************************************
        	 * Zend framevork validator existence zaznamu v databazi
        	 * 
        	$validator = new Zend_Validate_Db_NoRecordExists(
										array(
												'table' => 'file',
												'field' => 'file_name'
											)
						);
			if ($validator->isValid($username)) {
				// username appears to be valid
			} else {
				// username is invalid; print the reason
				$messages = $validator->getMessages();
				foreach ($messages as $message) {
					echo "$message\n";
				}
			}
        	**********************************************************************/
        
        
        //vyhodnoceni zdali jde o tabulku aktualniho modelu
        if (array_key_exists('foreignTable', $options)){
        	//tabulka cizy
        	$this->_foreignTable['foreign'] = TRUE;
        	$this->_foreignTable['options'] = $options;
        	echo "<p>"."foreign"."</p>";
        }else {
        	//tabulka aktualniho modelu
        	if (!array_key_exists('column', $options)) {
            	$options['column'] = 0;
        	}
        
        	$this->setColumn($options['column']);
        	if (array_key_exists('id', $options)) {
            	$this->setId($options['id']);
        	}
        
    		if (array_key_exists('model', $options)) {
            	$this->setModel($options['model']);
        	}
        }
    }
    
    
	/**
     * Returns the column option
     *
     * @return string
     */
    public function getColumn()
    {
        return $this->_column;
    }

    /**
     * Sets the storage option
     *
     * @param   storage
     * @throws Zend_Validate_Exception
     * @return Zend_Validate_StringLength Provides a fluent interface
     */
    public function setModel($model)
    {
    	$this->_model = $model;
        return $this;
    }

    /**
     * Returns the storage option
     *
     * @return 
     */
    public function getModel()
    {
        return $this->_model;
    }
    
    
/**
     * Sets the column option
     *
     * @param  string $min
     * @throws Zend_Validate_Exception
     * @return Zend_Validate_StringLength Provides a fluent interface
     */
    public function setColumn($column)
    {
        $this->_column = $column;
        return $this;
    }

    /**
     * Returns the id option
     *
     * @return integer
     */
    public function getId()
    {
        return $this->_id;
    }
    /**
     * Sets the id option
     *
     * @param  integer
     * @throws Zend_Validate_Exception
     * @return Zend_Validate_StringLength Provides a fluent interface
     */
    public function setId($id)
    {
        $this->_id = (integer) $id;
        return $this;
    }
    
    
	public function isValid($value, $file = null)
	{
		//$directories = $this->getDirectory(true);
		//vyhodnoceni zdali jde o tabulku aktualniho modelu
		if ($this->_foreignTable['foreign']){
			//tabulka cizy
			$validator = new Zend_Validate_Db_NoRecordExists($this->_foreignTable['options']['foreignTable']);
			if (!$validator->isValid($value)) {
				// username appears to be valid
				$this->_foreignTable['validate'] = TRUE;
				echo "<p>"."foreign TRUE"."</p>";
				return true;
			} else {
				$this->_foreignTable['validate'] = FALSE;
				echo "<p>"."foreign FALSE"."</p>";
				return $this->_throw($file, self::DOES_ENTRYEXISTDB);
			}
		}else {
			//tabulka aktualniho modelu
        	if (($file !== null) and (!empty($file['destination']))) {
        	    $directories[] = $file['destination'];
        	} else if (!isset($file['name'])) {
        	    $file['name'] = $value;
        	}
        	if (is_null($this->_id)){
        		$select = $this->_model->getStorage()->select(current($this->_model->getStorage()->info('primary')))
        									->where($this->_column.' = ?',$file['name']);
        	}else {
        		$select = $this->_model->getStorage()->select(current($this->_model->getStorage()->info('primary')))
        									->where($this->_column.' = ?',$file['name'])
        									->where(current($this->_model->getStorage()->info('primary')).' != ?',$this->_id);
        	}
        	$sameRow = $this->_model->getStorage()->fetchAll($select);
        	//echo "<p>".$select."</p>";
        	if (count($sameRow) > 0){
        		return $this->_throw($file, self::DOES_EXISTDB);
        	} else {
        	    return true;
        	}
		}
	}
	
	
/**
     * Throws an error of the given type
     *
     * @param  string $file
     * @param  string $errorType
     * @return false
     */
    protected function _throw($file, $errorType)
    {
    	if (!$this->_foreignTable['foreign']){
        	if ($file !== null) {
            	$this->_value = $file['name'];
        	}
    	}

        $this->_error($errorType);
        return false;
    }
}