#!/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 WriteResultMols(oms, lig, prot, wat, other):
    if not lig.NumAtoms() == 0:
        oechem.OEWriteMolecule(oms, lig)

    if not prot.NumAtoms() == 0:
        oechem.OEWriteMolecule(oms, prot)

    if not wat.NumAtoms() == 0:
        oechem.OEWriteMolecule(oms, wat)

    if not other.NumAtoms() == 0:
        oechem.OEWriteMolecule(oms, other)


def SplitMolComplex(oms, inmol, splitCovalent, separateResidues):
    # limiting lig, prot and wat to just near the first binding site
    # (a very common pattern)

    lig = oechem.OEGraphMol()
    prot = oechem.OEGraphMol()
    wat = oechem.OEGraphMol()
    other = oechem.OEGraphMol()

    if not splitCovalent and not separateResidues:
        # @ <SNIPPET-SPLIT-MOL-COMPLEX-SIMPLE>
        # for input molecule inmol ...
        lig = oechem.OEGraphMol()
        prot = oechem.OEGraphMol()
        wat = oechem.OEGraphMol()
        other = oechem.OEGraphMol()

        if oechem.OESplitMolComplex(lig, prot, wat, other, inmol):
            # work with the output molecules lig, prot, ...
            # @ </SNIPPET-SPLIT-MOL-COMPLEX-SIMPLE>
            WriteResultMols(oms, lig, prot, wat, other)

    elif splitCovalent and not separateResidues:
        # @ <SNIPPET-SPLIT-MOL-COMPLEX-SPLIT-COVALENT>
        # given input and output molecules ...
        opt = oechem.OESplitMolComplexOptions()
        opt.SetSplitCovalent()

        if oechem.OESplitMolComplex(lig, prot, wat, other, inmol, opt):
            # ...
            # @ </SNIPPET-SPLIT-MOL-COMPLEX-SPLIT-COVALENT>
            WriteResultMols(oms, lig, prot, wat, other)
    elif not splitCovalent and separateResidues:
        # @ <SNIPPET-SPLIT-MOL-COMPLEX-SEPARATE-RES>
        opt = oechem.OESplitMolComplexOptions()
        opt.SetSeparateResidues()

        if not oechem.OESplitMolComplex(lig, prot, wat, other, inmol, opt):
            oechem.OEThrow.Fatal("Unable to split mol complex from %s" % inmol.GetTitle())
            # @ </SNIPPET-SPLIT-MOL-COMPLEX-SEPARATE-RES>
        else:
            WriteResultMols(oms, lig, prot, wat, other)
    else:
        # @ <SNIPPET-SPLIT-MOL-COMPLEX-OPTIONS>
        opt = oechem.OESplitMolComplexOptions()
        opt.SetSplitCovalent(splitCovalent)
        opt.SetSeparateResidues(separateResidues)

        if not oechem.OESplitMolComplex(lig, prot, wat, other, inmol, opt):
            oechem.OEThrow.Fatal("Unable to split mol complex from %s" % inmol.GetTitle())
            # @ </SNIPPET-SPLIT-MOL-COMPLEX-OPTIONS>
        else:
            WriteResultMols(oms, lig, prot, wat, other)


def SplitMolComplexAllSites(oms, inmol, splitCovalent):
    lig = oechem.OEGraphMol()
    prot = oechem.OEGraphMol()
    wat = oechem.OEGraphMol()
    other = oechem.OEGraphMol()

    if splitCovalent:
        # @ <SNIPPET-SPLIT-MOL-COMPLEX-ALL-SITES-SPLIT>
        opt = oechem.OESplitMolComplexOptions()
        allSites = 0
        opt.ResetFilters(allSites)
        opt.SetSplitCovalent()
        # @ </SNIPPET-SPLIT-MOL-COMPLEX-ALL-SITES-SPLIT>

        if oechem.OESplitMolComplex(lig, prot, wat, other, inmol, opt):
            WriteResultMols(oms, lig, prot, wat, other)
    else:
        # @ <SNIPPET-SPLIT-MOL-COMPLEX-ALL-SITES>
        opt = oechem.OESplitMolComplexOptions()
        allSites = 0
        opt.ResetFilters(allSites)
        # @ </SNIPPET-SPLIT-MOL-COMPLEX-ALL-SITES>

        if oechem.OESplitMolComplex(lig, prot, wat, other, inmol, opt):
            WriteResultMols(oms, lig, prot, wat, other)


def SplitMolComplexCombineFilters(oms, inmol):
    lig = oechem.OEGraphMol()
    prot = oechem.OEGraphMol()
    wat = oechem.OEGraphMol()
    other = oechem.OEGraphMol()

    # @ <SNIPPET-SPLIT-MOL-COMPLEX-COMBINE-FILTERS>
    opt = oechem.OESplitMolComplexOptions()
    p = opt.GetProteinFilter()
    w = opt.GetWaterFilter()
    opt.SetProteinFilter(oechem.OEOrRoleSet(p, w))

    opt.SetWaterFilter(oechem.OEMolComplexFilterFactory(oechem.OEMolComplexFilterCategory_Nothing))
    # @ </SNIPPET-SPLIT-MOL-COMPLEX-COMBINE-FILTERS>

    if oechem.OESplitMolComplex(lig, prot, wat, other, inmol, opt):
        WriteResultMols(oms, lig, prot, wat, other)


def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)

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

    iname = itf.GetString("-i")
    oname = itf.GetString("-o")

    ims = oechem.oemolistream()
    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!")

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

    allSites = itf.GetBool("-a")
    splitCovalent = itf.GetBool("-c")
    separateResidues = itf.GetBool("-s")
    combineFilters = itf.GetBool("-pw")
    if combineFilters:
        SplitMolComplexCombineFilters(oms, inmol)
    elif allSites:
        SplitMolComplexAllSites(oms, inmol, splitCovalent)
    else:
        SplitMolComplex(oms, inmol, splitCovalent, separateResidues)

    oms.close()


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

InterfaceData = '''
!BRIEF SplitMolComplexOptDoc.py <molfile> [<outfile>]

!PARAMETER -i
  !TYPE string
  !BRIEF Input molecule (usually a pdb file)
  !REQUIRED true
  !KEYLESS 1
!END
!PARAMETER -o
  !TYPE string
  !DEFAULT splitmolcomplex.oeb.gz
  !BRIEF Output molecule (usually an oeb)
  !REQUIRED false
  !KEYLESS 2
!END
!PARAMETER -a
  !TYPE bool
  !DEFAULT false
  !BRIEF If true, show all binding sites, not just the first
  !REQUIRED false
!END
!PARAMETER -c
  !TYPE bool
  !DEFAULT false
  !BRIEF If true, split covalent ligands
  !REQUIRED false
!END
!PARAMETER -s
  !TYPE bool
  !DEFAULT false
  !BRIEF If true, separate residues before recombining (to return just binding site res)
  !REQUIRED false
!END
!PARAMETER -pw
  !TYPE bool
  !DEFAULT false
  !BRIEF If true, combine protein and water into the same output mol (ignore other options)
  !REQUIRED false
!END'''

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