#!/usr/bin/env python
# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.
#
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of OpenEye products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. OpenEye 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 OpenEye 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 OpenEye be
# liable for any damages or liability in connection with the Sample Code
# or its use.

# @ <SNIPPET>
import sys
from openeye import oechem


def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oechem.OEConfigureSplitMolComplexOptions(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        oechem.OEThrow.Fatal("Unable to interpret command line!")

    if itf.GetBool("-verbose"):
        oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Verbose)

    iname = itf.GetString("-in")
    oname = itf.GetString("-out")

    ims = oechem.oemolistream()
    if not itf.GetUnsignedInt("-modelnum") == 1:
        ims.SetFlavor(oechem.OEFormat_PDB,
                      oechem.OEGetDefaultIFlavor(oechem.OEFormat_PDB) &
                      ~oechem.OEIFlavor_PDB_ENDM)
    if not ims.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    oms = oechem.oemolostream()
    if not oms.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    mol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ims, mol):
        oechem.OEThrow.Fatal("Cannot read input file!")

    if itf.GetBool("-verbose"):
        oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Verbose)

    opt = oechem.OESplitMolComplexOptions()
    oechem.OESetupSplitMolComplexOptions(opt, itf)

    # @ <SNIPPET-SPLIT-MOL-COMPLEX-LOWLEVEL-FRAGMENT>
    # for input molecule mol and options opt ...
    frags = oechem.OEAtomBondSetVector()

    if oechem.OEGetMolComplexFragments(frags, mol, opt):
        # ...
        # @ </SNIPPET-SPLIT-MOL-COMPLEX-LOWLEVEL-FRAGMENT>
        oechem.OEThrow.Verbose("Able to fragment mol complex from %s" % iname)
    else:
        oechem.OEThrow.Fatal("Unable to fragment mol complex from %s" % iname)

    # @ <SNIPPET-SPLIT-MOL-COMPLEX-LOWLEVEL-COMBINE>
    # for options opt and OEAtomBondSetVector frags produced earlier ...
    numSites = oechem.OECountMolComplexSites(frags)
    oechem.OEThrow.Verbose("sites %d" % numSites)

    lig = oechem.OEGraphMol()
    ligfilter = opt.GetLigandFilter()
    if not oechem.OECombineMolComplexFragments(lig, frags, opt, ligfilter):
        oechem.OEThrow.Warning("Unable to combine ligand frags from %s" % mol.GetTitle())

    protComplex = oechem.OEGraphMol()
    p = opt.GetProteinFilter()
    w = opt.GetWaterFilter()
    if not oechem.OECombineMolComplexFragments(protComplex, frags, opt, oechem.OEOrRoleSet(p, w)):
        oechem.OEThrow.Warning("Unable to combine complex frags from %s" % mol.GetTitle())
    # @ </SNIPPET-SPLIT-MOL-COMPLEX-LOWLEVEL-COMBINE>

    if not lig.NumAtoms() == 0:
        oechem.OEThrow.Verbose("  lig %s" % lig.GetTitle())
        oechem.OEWriteMolecule(oms, lig)

    if not protComplex.NumAtoms() == 0:
        oechem.OEThrow.Verbose(" prot %s" % protComplex.GetTitle())
        oechem.OEWriteMolecule(oms, protComplex)

    oms.close()


#############################################################################
# INTERFACE
#############################################################################

InterfaceData = '''
!BRIEF SplitMolComplexLowLevelDoc.py <inmol> [<outmol>]

!CATEGORY "input/output options :"
   !PARAMETER -in
      !ALIAS -i
      !TYPE string
      !BRIEF Input molecule (usually a pdb file)
      !VISIBILITY simple
      !REQUIRED true
      !KEYLESS 1
   !END

   !PARAMETER -out
      !ALIAS -o
      !TYPE string
      !DEFAULT splitmolcomplex.oeb.gz
      !BRIEF Output molecule (usually an oeb)
      !VISIBILITY simple
      !REQUIRED false
      !KEYLESS 2
   !END
!END

!CATEGORY "Display options :"
   !PARAMETER -verbose
      !ALIAS -v
      !TYPE bool
      !DEFAULT false
      !BRIEF If true, show molecule titles and number of binding sites
      !VISIBILITY simple
      !REQUIRED false
   !END
!END
'''

if __name__ == "__main__":
    sys.exit(main(sys.argv))
# @ </SNIPPET>
