/**********************************************************************
 *
 * querycache.cpp -- 
 * Copyright (C) 1999  The New Zealand Digital Library Project
 *
 * A component of the Greenstone digital library software
 * from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *********************************************************************/

#include "querycache.h"




resultcacheel::resultcacheel () 
{
  accessnum = -1;
}



querycache::querycache (int themaxcachesize)
{
  if (themaxcachesize < 1) themaxcachesize = 1;
  
  resultcache = new resultcacheel[themaxcachesize];

  maxcachesize = themaxcachesize;
  nextaccessnum = 1;
}

querycache::~querycache ()
{
  delete [] resultcache;
}

// returns true if the query was found in the cache
// if the query was found then queryresults contains
// the results
bool querycache::find (const queryparamclass &queryparams, 
		       queryresultsclass &queryresults)
{
  int i;

  for (i=0; i < maxcachesize; ++i)
    {
      if (resultcache[i].queryparameters == queryparams)
	{
	  queryresults = resultcache[i].queryresults;
	  resultcache[i].accessnum = getnextaccessnum ();
	  return true;
	}
    }

  return false;
}


void querycache::cache (const queryparamclass &queryparams,
	  const queryresultsclass &queryresults)
{
  int i = getfreecachenum();
  resultcache[i].queryparameters = queryparams;
  resultcache[i].queryresults = queryresults;
  resultcache[i].accessnum = getnextaccessnum ();
}

int querycache::getnextaccessnum ()
{
  return nextaccessnum++;
}

int querycache::getfreecachenum ()
{
  int i;
  int minaccessnum = 0;
  int minaccessi = 0;
  
  for (i=0; i < maxcachesize; ++i)
    {
      if (resultcache[i].accessnum < minaccessnum) {
	minaccessnum = resultcache[i].accessnum;
	minaccessi = i;
      }
    }

  return minaccessi;
}
