// -- servlet package
package servlets;


// -- java core packages
import java.io.*;
import java.util.*;
import java.sql.*;


// -- java extension packages
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;


// -- database package
import database.*;


public class EimeriaSpeciesTag extends BodyTagSupport {


    /** Nome da especie */
    private String speciesName = null;
    /** Contador */
    private int counter = 0;
    /** Iterator */
    private Iterator iterator = null;
    /** Recebe o resultado da busca no banco */
    private DBResults results = null;
    /** Numero de linhas */
    private int num = 0;


    /**
     *
     */

    public int doStartTag() throws JspException {

	String query = 
	    "SELECT distinct c.classification_name as species_name" +
	    " FROM" + 
	    " scar s," +
	    " classification c," +
	    " classification_parent cp" +
	    " WHERE" +
	    " s.genus_id = cp.classification_parent AND" +
	    " cp.classification_descendant = c.classification_id";


	// -- executa uma query no banco de dados
	results = DatabaseUtilities.getQueryResults( "org.postgresql.Driver",
						     "jdbc:postgresql://endereco_do_banco:5432/scarsdb",
						     "postgres",
						     "senha",
						     query,
						     true );
	
	num = results.getRowCount();
	
	if( num > 0 ) {
	    String [] species = results.getRow( counter );
	    speciesName = species[ 0 ];
	    processNext();
	    counter++;
	    return EVAL_BODY_TAG;
	} else
	    return SKIP_BODY;

    }

    
    /**
     *
     */

    public int doAfterBody() {

	try {
	    bodyContent.writeOut( getPreviousOut() );
	} catch( IOException ioException ) {
	    ioException.printStackTrace();
	    return SKIP_BODY;
	}

	bodyContent.clearBody();

	if( counter < num ) {
	    String [] species = results.getRow( counter );
	    speciesName = species[ 0 ];
	    processNext();
	    counter++;
	    return EVAL_BODY_TAG;
	} else
	    return SKIP_BODY;

    }


    /**
     *
     */

    public void processNext() {

	// -- set next species
	pageContext.setAttribute( "speciesName", speciesName );

    }

}
