/* 
(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 "oesystem.h"
#include "oechem.h"
#include "oebio.h"
#include "oeopt.h"
#include "oemolpotential.h"
#include "oemmff.h"
#include "oesmirnoff.h"
#include "oeff.h"

/////////////////////////////////////////////////////////////////////////////
// The following is an example to show how to evaluate energies            //
// of a small molecule and obtain various energy components.               //
/////////////////////////////////////////////////////////////////////////////

class FFOptions : public OESystem::OEOptions
{
public:
  FFOptions(std::string name = "FFOptions")
    : OESystem::OEOptions(name)
  {
    OESystem::OEStringParameter ffType("-ff", "parsley");
    ffType.AddLegalValue("parsley");
    ffType.AddLegalValue("mmff94");
    ffType.AddLegalValue("mmff94s");
    ffType.SetBrief("Force field type");
    m_fftype = AddParameter(ffType);
  }

  FFOptions* CreateCopy() const { return new FFOptions(*this); }

  OEMolPotential::OEForceField* GetFF() const
  {
    std::string ff = m_fftype->GetStringValue();
    if (ff.empty())
      ff = m_fftype->GetStringDefault();

    if (ff == "mmff94")
      return new OEMolMMFF::OEMMFF();
    else if (ff == "mmff94s")
      return new OEMolMMFF::OEMMFF(OEMolMMFF::OEMMFF94sParams());
    else
      return new OEMolSmirnoff::OEParsley();
  }

private:
  OESystem::OEParameter* m_fftype;
};


int main(int argc, char* argv[])
{
  FFOptions ffOpts;
  OEChem::OESimpleAppOptions opts(ffOpts, "FFOptimize", OEChem::OEFileStringType::Mol3D,
    OEChem::OEFileStringType::Mol3D);
  if (OESystem::OEConfigureOpts(opts, argc, argv, false) == OESystem::OEOptsConfigureStatus::Help)
    return 0;
  ffOpts.UpdateValues(opts);

  OEChem::oemolistream ifs;
  if (!ifs.open(opts.GetInFile()))
    OESystem::OEThrow.Fatal("Unable to open %s for reading", opts.GetInFile().c_str());

  OEChem::oemolostream ofs;
  if (!ofs.open(opts.GetOutFile()))
    OESystem::OEThrow.Fatal("Unable to open %s for writing", opts.GetOutFile().c_str());

  std::unique_ptr<OEMolPotential::OEForceField> ff(ffOpts.GetFF());

  OEChem::OEMol mol;
  while (OEChem::OEReadMolecule(ifs, mol))
  {
    if (!ff->PrepMol(mol) || !ff->Setup(mol))
    {
      OESystem::OEThrow.Warning("Unable to process molecule: title = %s", mol.GetTitle());
      OEChem::OEWriteMolecule(ofs, mol);
      continue;
    }
    
    std::vector<double> vecCoords(3*mol.GetMaxAtomIdx());
    for (OESystem::OEIter<OEChem::OEConfBase> conf = mol.GetConfs(); conf; ++conf)
    {
      OESystem::OEThrow.Info("Molecule: %s Conformer: %d", mol.GetTitle(), conf->GetIdx()+1);     
      conf->GetCoords(&vecCoords[0]);

      // Calculate energy
      double energy = (*ff)(&vecCoords[0]);
      OESystem::OEThrow.Info("Initial energy: %f kcal/mol", energy);

      // Optimize the ligand
      OEOpt::OEBFGSOpt optimizer;
      energy = optimizer(*ff, &vecCoords[0], &vecCoords[0]);
      OESystem::OEThrow.Info("Optimized energy: %f kcal/mol", energy);
      conf->SetCoords(&vecCoords[0]);
    }
    OEChem::OEWriteMolecule(ofs, mol);
  }

  return 0;
}
