#include "available.h"
#define RELEASE

int rackStatus(ResultSet rackdata,string name){
  rackdata.rewind();
  do
    {
      if(name==(string)rackdata["acronym"])
	return (int)rackdata["status"];
    }while(rackdata.next());
  return -1;
}

int rackStatus(ResultSet rackdata,int idx){
  rackdata.rewind();
  do
    {
      if(idx==(int)rackdata["idx"])
	return (int)rackdata["status"];
    }while(rackdata.next());
  return -1;
}

bool available(ResultSet rackdata,vector<vector<int> > constraints,vector<vector<int> > triggers,string name){
  int racknum=-1;
  rackdata.rewind();
  do
    {
      string current=rackdata["acronym"];
      if(name==current)
	{
	  racknum=(int)rackdata["idx"];
	  break;
	}
    }while(rackdata.next());
  if(racknum==-1)
    {
      cout<<"Bad arguments to available(): \""<<name<<"\" is not a rack name.\n";
      exit(1);
    }

#ifndef RELEASE
  cout<<"name=\""<<name<<"\"\n"<<"racknum="<<racknum<<'\n';
#endif

  // Check the obvious, is status!=O
  int status=rackStatus(rackdata,name);
#ifndef RELEASE
  cout<<name<<"'s status="<<status<<'\n';
#endif
  if(status!=3)return true;

  if(constraints.size()!=triggers.size())
    {
      cout<<"Bad arguments to available(): triggers and constraints vectors should be of equal length.\n";
      exit(1);
    }

  for(int n=0;n!=constraints.size();n++)
    {
      vector<int> constraint=constraints[n];
      vector<int> trigger=triggers[n]; // Constraints and triggers are the same size
      bool included=false;
      bool possibletrigger=false;
      for(int j=0;j!=constraint.size();j++)
	{
	  if(constraint[j]==racknum)
	    {
	      included=true;
#ifndef RELEASE
	      cout<<name<<" is included in a constraint, "<<n<<'\n';
#endif
	    }
	}
      for(int j=0;j!=trigger.size();j++)
	{
	  if(rackStatus(rackdata,trigger[j])!=3)
	    {
#ifndef RELEASE
	      cout<<j<<" is a valid trigger in constraint "<<n<<'\n';
#endif
	      possibletrigger=true;
	    }
	}
      if(included && possibletrigger)return true;
    }
  return false;
}
