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

namespace jet {

   __mysql::__mysql(coreutils::ZString &in, coreutils::MString &parent, Global &global) : Tag(in, parent, global) {
      
      if(!variableDefined("host"))
	throw coreutils::Exception("host must be specified for mysql tag.");
      if(!variableDefined("database"))
	throw coreutils::Exception("database must be specified for mysql tag.");
      if(!variableDefined("user"))
	throw coreutils::Exception("user must be specified for mysql tag.");
      if(!variableDefined("password"))
	throw coreutils::Exception("password must be specified for mysql tag.");

      sessionId = variables["sessionid"];
      
      global.addSession(sessionId, this);
      
      mysql = mysql_init(NULL);
      mysql = mysql_real_connect(mysql, variables["host"].c_str(), variables["user"].c_str(), variables["password"].c_str(), variables["database"].c_str(), 0, NULL, 0);            
      
      if(!mysql)
	throw coreutils::Exception("database and host parameters are not valid.");
      
      std::cout << "mysql: " << mysql << std::endl;

      processContainer(container);
      
   }

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

   void __mysql::query(coreutils::MString query) {
      std::cout << "q: " << query << std::endl;
      int rc = mysql_real_query(mysql, query.getData(), query.getLength());
      std::cout << "rc: " << rc << std::endl;
      result = mysql_store_result(mysql);
      std::cout << "result: " << result << std::endl;
      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) {
      if(column == "#")
	return NbrOfRows;
      MYSQL_FIELD *field;
      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.");
   }
   
}
