/*****************************************************************************
 * Copyright (c) 2005  Daniel Lerch Hostalot <http://daniellerch.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a 
 * copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 ****************************************************************************/



#include "resultset.h"


resultset_t *resultset_new(MYSQL_RES* res) { 

   resultset_t *rs;
   rs = (resultset_t*)malloc(sizeof(resultset_t));

   rs->resultset = res; 
   rs->nfield=0; 

   return rs;
}


int resultset_next(resultset_t *rs) 
{
   if ( (rs->row = mysql_fetch_row(rs->resultset))==NULL ) {

      return 0;
   }
   else { 

      rs->nfield = 0;
      return 1;
   }
}

int resultset_next_field(resultset_t *rs) {


   if (rs->nfield < mysql_num_fields (rs->resultset) ) {

      rs->nfield++;
      return 1;
   }

   return 0;
}

char *resultset_get_field(resultset_t *rs)
{

   static char field[256];

   if (rs->nfield==0) strcpy(field, "");
   else {

      if (rs->row[rs->nfield-1])
         snprintf (field, sizeof(field), "%s", rs->row[rs->nfield-1]);
      else
         strcpy(field, "");
   }

   return field;
}


char *resultset_get_field_by_name(resultset_t *rs, char* name) 
{
   int i;
   MYSQL_FIELD *fields;

   /*
    * El rendimiento no es bueno. Habria que introducir los datos del
    * resultset en una tabla de dispersion en la primera solicitud y
    * realizar los accesos siguientes a la misma.
    */

   for (i=0;i<mysql_num_fields (rs->resultset);i++) {

      fields = mysql_fetch_fields(rs->resultset);

      if (strcmp(fields[i].name, name)==0) {

         if (rs->row[i]) return rs->row[i];
         else return "";
      }
   }

   return "";
}


void resultset_free(resultset_t *rs) 
{
   if (rs->resultset) mysql_free_result (rs->resultset); 
}


