#!/usr/bin/env python
# (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.


from openeye import oechem
from openeye import oebioisostere

class QueryOptions(oechem.OEOptions):
    def __init__(self):
        oechem.OEOptions.__init__(self, "2MolLinkerQueryOptions")

        idxNo1Param = oechem.OEUIntParameter("-atomIndicesNo1")
        idxNo1Param.SetIsList(True)
        idxNo1Param.SetRequired(True)
        idxNo1Param.SetBrief("Index of atoms in fragment No.1")
        self._idxNo1Param = self.AddParameter(idxNo1Param)
        
        idxNo2Param = oechem.OEUIntParameter("-atomIndicesNo2")
        idxNo2Param.SetIsList(True)
        idxNo2Param.SetRequired(True)
        idxNo2Param.SetBrief("Index of atoms in fragment No.2")
        self._idxNo2Param = self.AddParameter(idxNo2Param)

        duParam = oechem.OEFileStringParameter("-du", oechem.OEFileStringType_DU)
        duParam.SetBrief("Design unit containing protein target for bump check")
        self._duParam = self.AddParameter(duParam)

        maskParam = oechem.OEUIntParameter("-proteinMask", oechem.OEDesignUnitComponents_TargetComplexNoSolvent)
        maskParam.SetBrief("Design unit mask to identify protein target")
        self._maskParam = self.AddParameter(maskParam)
        
        selectDUParam = oechem.OEFileStringParameter("-selectDU", oechem.OEFileStringType_DU)
        selectDUParam.SetBrief("Design unit containing select protein for bump check")
        self._selectDUParam = self.AddParameter(selectDUParam)

        maskSelectParam = oechem.OEUIntParameter("-proteinSelectMask", oechem.OEDesignUnitComponents_TargetComplexNoSolvent)
        maskSelectParam.SetBrief("Design unit mask to identify select protein target")
        self._maskSelectParam = self.AddParameter(maskSelectParam)

    def CreateCopy(self):
        return self

    def GetFirstMolIndices(self):
        indices = []
        for idx in self._idxNo1Param.GetStringValues():
            indices.append(int(idx))
        return indices

    def GetSecondMolIndices(self):
        indices = []
        for idx in self._idxNo2Param.GetStringValues():
            indices.append(int(idx))
        return indices

    def GetDU(self):
        ifs = oechem.oeifstream()
        if not self._duParam.GetHasValue():
            return None
        if not ifs.open(self._duParam.GetStringValue()):
            oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetInFile())
        du = oechem.OEDesignUnit()
        if not oechem.OEReadDesignUnit(ifs, du):
            oechem.OEThrow.Fatal("Unable to read design unit")
        return du

    def GetProteinMask(self):
        mask = self._maskParam.GetStringValue()
        if mask == "":
            mask = self._maskParam.GetStringDefault()
        return int(mask)


    def GetSelectDU(self):
        ifs = oechem.oeifstream()
        if not self._selectDUParam.GetHasValue():
            return None
        if not ifs.open(self._selectDUParam.GetStringValue()):
            oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetInFile())
        selectDU = oechem.OEDesignUnit()
        if not oechem.OEReadDesignUnit(ifs, selectDU):
            oechem.OEThrow.Fatal("Unable to read design unit")
        return selectDU

    def GetSelectProteinMask(self):
        mask = self._maskSelectParam.GetStringValue()
        if mask == "":
            mask = self._maskSelectParam.GetStringDefault()
        return int(mask)

def main(argv=[__name__]):
    queryOpts = QueryOptions()
    opts = oechem.OERefInputAppOptions(queryOpts, "2MolLinkerBroodQuery", oechem.OEFileStringType_Mol3D, oechem.OEFileStringType_Mol3D, oechem.OEFileStringType_Mol3D , "-in2")
    if oechem.OEConfigureOpts(opts, argv, False) == oechem.OEOptsConfigureStatus_Help:
        return 0
    queryOpts.UpdateValues(opts)

    ifs = oechem.oemolistream()
    if not ifs.open(opts.GetInFile()):
        oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetInFile())
        
    rfs = oechem.oemolistream()
    if not rfs.open(opts.GetRefFile()):
        oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetRefFile())
        
    ofs = oechem.oemolostream()
    if not ofs.open(opts.GetOutFile()):
        oechem.OEThrow.Fatal("Unable to open %s for writing" % opts.GetOutFile())

    firstMol = oechem.OEMol()
    if not oechem.OEReadMolecule(ifs, firstMol):
        oechem.OEThrow.Fatal("Unable to load molecule 1")
        
    secondMol = oechem.OEMol()
    if not oechem.OEReadMolecule(rfs, secondMol):
        oechem.OEThrow.Fatal("Unable to load molecule 2")

    firstMolIndices = queryOpts.GetFirstMolIndices()
    firstMolAtoms = []
    for idx in firstMolIndices:
        firstMolAtom = firstMol.GetAtom(oechem.OEHasAtomIdx(idx))
        if not firstMolAtom:
            oechem.OEThrow.Fatal("Invalid atom index %d" % idx)
        firstMolAtoms.append(firstMolAtom)
  
    secondMolIndices = queryOpts.GetSecondMolIndices()
    secondMolAtoms = []
    for idx in secondMolIndices:
        secondMolAtom = secondMol.GetAtom(oechem.OEHasAtomIdx(idx))
        if not secondMolAtom:
            oechem.OEThrow.Fatal("Invalid atom index %d" % idx)
        secondMolAtoms.append(secondMolAtom)

    firstMolSelection = oechem.OEAtomBondSet()
    firstMolSelection.AddAtoms(firstMolAtoms)

    secondMolSelection = oechem.OEAtomBondSet()
    secondMolSelection.AddAtoms(secondMolAtoms)
    
    query = oebioisostere.OEBroodQuery()
    du = queryOpts.GetDU()
    selectDU = queryOpts.GetSelectDU()
    
    if du is None and selectDU is None:
        retCode = oebioisostere.OECreateBroodQuery(query, firstMol, secondMol, firstMolSelection, secondMolSelection)
    elif du is None and selectDU is not None:
        passingProteinSelect = True
        retCode = oebioisostere.OECreateBroodQuery(query, firstMol, secondMol, firstMolSelection, secondMolSelection, selectDU, queryOpts.GetSelectProteinMask(), passingProteinSelect)
    elif selectDU is None:
        retCode = oebioisostere.OECreateBroodQuery(query, firstMol, secondMol, firstMolSelection, secondMolSelection, du, queryOpts.GetProteinMask())
    else:
        retCode = oebioisostere.OECreateBroodQuery(query, firstMol, secondMol, firstMolSelection, secondMolSelection, du, queryOpts.GetProteinMask(), selectDU, queryOpts.GetSelectProteinMask())
    
    if retCode != oebioisostere.OEBroodStatusCode_Success:
        oechem.OEThrow.Fatal("%s" % oebioisostere.OEGetBroodStatus(retCode))
    oebioisostere.OEWriteBroodQuery(ofs, query)

if __name__ == "__main__":
    import sys
    sys.exit(main(sys.argv))
