<?php
/**
 * Species class
 */
class Species {
	var $tsn;
	var $complete_name;
	var $familiar_name;
	
    function __construct( $tsn = null ){
		if ( is_null( $tsn ) == false ) {
			try {
				$this->load ( $tsn );
			} catch ( Exception $ex ) {
				// log exception
			}
		}
	}
	
	/**
	 * load a Pet into a Object
	 * 
	 * @param mixed $tsn
	 * @return $this
	 */
    public function load( $tsn ) {
		$con = new Connection ();
		$sql = "SELECT * 
					FROM species 
					WHERE tsn = " . $tsn;
		
		// execute query...
		$rs = $con->selectOneRow ( $sql );
		
		// if specie exists into the system
		if( is_array( $rs ) == true && empty( $rs ) == false ){
			$this->tsn					= $rs ['tsn'];
			$this->completename			= $rs ['complete_name'];
			$this->familiar_name		= $rs ['familiar_name'];
		}
			
		$con->close ();
		return $this;
	}
	
		
	public function save() {
		$con = new Connection ();

		$sql = "INSERT into species 
				(
				tsn,
				complete_name,
				familiar_name
				)values(" 
					. "'" . $this->tsn . "', " 
					. "'" . $this->complete_name . "', " 
					. "'" . $this->familiar_name . "' " 
					. ")";
		
		$rv = $con->execute( $sql );
		
		if ($rv === true) {
			$con->commit();
		}else{
			Watchdog::write( Watchdog::TYPE_DATABASE, $con->sqlstate.': '.$con->sql, 0, Watchdog::WATCHDOG_WARNING );
			$con->rollback();
		}

		$con->close();
		return $rv;
	}
	
	public function delete() {
		$con = new Connection ();

		$sql = "DELETE FROM species 
				WHERE tsn = '" . $this->tsn . "' LIMIT 1";
		
		// d( $sql );
		
		$rv = $con->execute( $sql );
		
		if ($rv === true) {
			$con->commit();
		}else{
			Watchdog::write( Watchdog::TYPE_DATABASE, $con->sqlstate.': '.$con->sql, 0, Watchdog::WATCHDOG_WARNING );
			$con->rollback();
		}

		$con->close();
		return $rv;
	}
	
	public static function in_use( $tsn ){
		$con = new Connection();
		$sql = "SELECT * 
					FROM species 
					WHERE tsn = " . $tsn . "
					AND tsn IN (
						SELECT DISTINCT tsn FROM pets
						)";
		
		
		$rv = $con->execute( $sql );
		
		if( empty( $rv ) == true ){
			return false;
		}else{
			return true;
		}
	}
	
	public static function exists( $tsn ){
		$species = new Species( $tsn );
		if( empty( $species->tsn ) == true ){
			return false;
		}else{
			return true;
		}
	}
	

	
}
?>
