#include "./DataBase.hh"
#include "./DataBaseNote.hh"
#include <pgsql/libpq-fe.h>
#include <stdlib.h>
#include <string.h>
#include "Memory.h"


DataBaseNote::DataBaseNote(Property* p)
{
  Prop = p;

  DataBase::SetDataBaseInfo(Prop->GetHostName(),Prop->GetPortName(),Prop->GetdbName());
}

void DataBaseNote::SetKey(char* AtomName, char* ResName , int ResNum)
{
 
  char* sql;
  sql = (char*)memoryAllocate(sizeof(char)*300, "Homology::SetKey");
  char* memo;
  memo = (char*)memoryAllocate(sizeof(char)*300, "Homology::SetKey");
  
  sprintf(sql, "SELECT key FROM %s WHERE atomname ~ '%s' and resname ~ '%s' and resnum = %d",
  	  Prop->GetNoteTableName(),AtomName,ResName,ResNum);
  res = PQexec(con, sql);
  
    if((PQgetvalue(res,PQntuples(res)-1 , PQnfields(res)-1))==NULL){
      //Create
      
      PQclear(res);
      printf("Please Write Your Memo!!\n");
      scanf("%s",memo);
      sprintf(sql, "INSERT INTO %s VALUES('%s','%s',%d,'NOW','%s',1)",
	      Prop->GetNoteTableName(),AtomName,ResName,ResNum,memo);
      res = PQexec(con, sql);
      PQclear(res);

    }else{

      int mode = 0;
      printf("1:Show   2:OverWrite  3:Delete >>>");
      scanf("%d",&mode);
 
      switch(mode){
      case 1:
	
	sprintf(sql, "SELECT atomname,resname,resnum,date,memo FROM %s WHERE atomname ~ '%s' and resname ~ '%s' and resnum = %d",Prop->GetNoteTableName(),AtomName,ResName,ResNum);
	
	res = PQexec(con, sql);    
	printf("Atom\tResNeme\tResNum\twrittenDate\tmemo\n");
	DataBase::DisplayAll(res);
	PQclear(res);

	break;

      case 2:

	printf("Please Write Your Memo!!\n");
	scanf("%s",memo);
	sprintf(sql, "UPDATE %s SET memo = '%s', date = 'NOW' WHERE atomname ~ '%s' and resname ~ '%s' and resnum = %d",
		Prop->GetNoteTableName(),memo,AtomName,ResName,ResNum);
	res = PQexec(con, sql);
	PQclear(res);
	break;

      case 3:
	sprintf(sql, "DELETE FROM %s WHERE atomname ~ '%s' and resname ~ '%s' and resnum = %d",
		Prop->GetNoteTableName(),AtomName,ResName,ResNum);
	res = PQexec(con, sql);
	PQclear(res);
	break;	

      default:

	break;

      }
    }
}
