/* 
(C) 2022 Cadence Design Systems, Inc. (Cadence) 
All rights reserved.
TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
provided to current licensees or subscribers of Cadence products or
SaaS offerings (each a "Customer").
Customer is hereby permitted to use, copy, and modify the Sample Code,
subject to these terms. Cadence claims no rights to Customer's
modifications. Modification of Sample Code is at Customer's sole and
exclusive risk. Sample Code may require Customer to have a then
current license or subscription to the applicable Cadence offering.
THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED.  OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
liable for any damages or liability in connection with the Sample Code
or its use.
*/
#include "openeye.h"
#include "oefastrocs.h"
#include "oechem.h"
#include "oesystem.h"

#include "bestshapeoverlaymulticonfquery.itf"

using namespace OEFastROCS;
using namespace OEChem;
using namespace OESystem;
using namespace std;

int main(int argc, char *argv[]) 
{
  OEInterface itf(InterfaceData, argc, argv);
  
  string dbname = itf.Get<string>("-dbase");
  if (OEIsGZip(dbname.c_str()))
    OEThrow.Fatal("%s is an unsupported database file format as it is gzipped.\n"
    "Preferred formats are .oeb, .sdf or .oez", dbname.c_str());

  if(!OEFastROCSIsGPUReady()) 
  {
    OEThrow.Info("No supported GPU available");
    return 0;
  }

  // set options
  OEShapeDatabaseOptions opts;
  opts.SetLimit(itf.Get<int>("-nHits"));
  OEThrow.Info("Number of hits set to %u", opts.GetLimit());
  if(itf.Get<float>("-cutoff"))
  {
    if(itf.Get<float>("-cutoff") >= 0)
    {
       opts.SetCutoff(itf.Get<float>("-cutoff"));
       OEThrow.Info("Cutoff set to %f", itf.Get<float>("-cutoff"));
    } 
    else
      OEThrow.Fatal("Cutoff must be greater than 0");
  }

  if(itf.Get<bool>("-tversky"))
    opts.SetSimFunc(OEShapeSimFuncType::Tversky);

  // read in database
  oemolistream ifs;
  if(!ifs.open(dbname))
    OEThrow.Fatal("Unable to open " + dbname);

  OEThrow.Info("Opening database file " + dbname);
  OEWallTimer timer;
  OEShapeDatabase dbase;
  OEMolDatabase moldb;
  if(!moldb.Open(ifs))
    OEThrow.Fatal("Unable to open '" + dbname + "'");

  OEThreadedDots dots(10000, 200, "conformers");
  if(!dbase.Open(moldb, dots))
    OEThrow.Fatal("Unable to initialize OEShapeDatabase on '" + dbname + "'");

  dots.Total();
  OEThrow.Info("%f seconds to load database", timer.Elapsed());
  OEIter<const string> i = itf.GetList<string>("-query");
  for(; i; ++i) 
  {
    string qfname = *i;

    // read in query
    oemolistream qfs;
    if(!qfs.open(qfname))
      OEThrow.Fatal("Unable to open '" + qfname + "'");
    
    OEMol mcmol;
    if(!OEReadMolecule(qfs, mcmol))
      OEThrow.Fatal("Unable to ready query from '" + qfname + "'");
    qfs.rewind();

    string ext = OEGetFileExtension(qfname.c_str());
    unsigned int qmolidx = 0;
    while(OEReadMolecule(qfs, mcmol)) 
    {
      // write out to a file name based on molecule title
      oemolostream ofs;
      string moltitle = mcmol.GetTitle();
      if(moltitle.size() == 0)
        moltitle = OENumberToString(qmolidx);

      string ofname = moltitle + "_results." + ext;
      if(!ofs.open(ofname))
        OEThrow.Fatal("Unable to open '" + qfname + "'");

      OEThrow.Info("Searching for %s of %s (%u conformers)", 
                    moltitle.c_str(), qfname.c_str(), mcmol.NumConfs());

      unsigned int qconfidx = 0;
      OEIter<OEConfBase> conf = mcmol.GetConfs();
      for(; conf; ++conf) 
      {
        OEIter<OEShapeDatabaseScore> score = dbase.GetSortedScores(conf, opts);
        for(; score; ++score)
        {
          OEMol dbmol;
          unsigned int dbmolidx = (unsigned) score->GetMolIdx();
          if(!moldb.GetMolecule(dbmol, dbmolidx)) 
          {
            OEThrow.Warning("Unable to retrieve molecule '%u' from the database", dbmolidx);
            continue;
          }

          OEGraphMol mol(*dbmol.GetConf(OEHasConfIdx(score->GetConfIdx())));
          OESetSDData(mol, "QueryConfIdx", OENumberToString(qconfidx));
          OESetSDData(mol, "ShapeTanimoto", OENumberToString(score->GetShapeTanimoto()));
          OESetSDData(mol, "ColorTanimoto", OENumberToString(score->GetColorTanimoto()));
          OESetSDData(mol, "TanimotoCombo", OENumberToString(score->GetTanimotoCombo()));
          score->Transform(mol);

          OEWriteMolecule(ofs, mol);                    
        }               

        ++qconfidx; 
      }

      OEThrow.Info("%u conformers processed", qconfidx);
      OEThrow.Info("Wrote results to " + ofname);
      ofs.close();
    }

    ++qmolidx;
  }   

  return 0;     
}
