#include "__mysql.h"
#include "Exception.h"
#include <iostream>

namespace jet {

   __mysql::__mysql(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, this) {
      
      if(!keywordDefined("host"))
	throw coreutils::Exception("host must be specified for mysql tag.");
      if(!keywordDefined("database"))
	throw coreutils::Exception("database must be specified for mysql tag.");
      if(!keywordDefined("user"))
	throw coreutils::Exception("user must be specified for mysql tag.");
      if(!keywordDefined("password"))
	throw coreutils::Exception("password must be specified for mysql tag.");
            
      sessionId = keywords[resolveKeyword("sessionid")];
      
      global.addSession(sessionId, this);
      
      mysql = mysql_init(NULL);
      mysql = mysql_real_connect(mysql,
				 keywords[resolveKeyword("host")].c_str(),
				 keywords[resolveKeyword("user")].c_str(),
				 keywords[resolveKeyword("password")].c_str(),
				 keywords[resolveKeyword("database")].c_str(), 0, NULL, 0);            
      
      if(!mysql)
	throw coreutils::Exception("database and host parameters are not valid.");

      processContainer(container);
      
   }

   __mysql::~__mysql() {
      global.removeSession(sessionId);
      mysql_free_result(result);
      mysql_close(mysql);
   }

   void __mysql::query(coreutils::MString query) {
      int rc = mysql_real_query(mysql, query.getData(), query.getLength());
      result = mysql_store_result(mysql);
      if(result) {
	 row = mysql_fetch_row(result);
	 fieldLength = mysql_fetch_lengths(result);
	 qFields = mysql_num_fields(result);
      }
   }

   void __mysql::nextRow() {
      row = mysql_fetch_row(result);
      fieldLength = mysql_fetch_lengths(result);
   }

   bool __mysql::hasRow() {
      return row != NULL;
   }
   
   coreutils::ZString __mysql::getColumnValue(coreutils::ZString column) {
      MYSQL_FIELD *field;      
      if(column == "?#") {
	 nbrOfColumns = (int)qFields;
	 return nbrOfColumns;
      } else if(column.ifNext("#")) {
	 if(column.eod()) {
	    nbrOfRows = (int)mysql_num_rows(result);
	    return nbrOfRows;
	 } else {
	    std::cout << "[" << column.unparsed() << "]" << std::endl;
	    int index = column.asInteger();
	    std::cout << "integer: " << index << std::endl;
	    field = mysql_fetch_field_direct(result, index - 1);
	    return coreutils::ZString(field->name);	 
	 }
      }
            
      for(int ix = 0; ix < qFields; ++ix) {
	 field = mysql_fetch_field_direct(result, ix);
	 if(column.equals((char *)field->name)) {
	    return coreutils::ZString(row[ix], fieldLength[ix]);
	 }	 
      }
      throw coreutils::Exception("column does not exist in session result.");
   }
   
}
