#!/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.
import sys
from openeye import oechem


# @ <SNIPPET-PREDICATE>
class MoleculeWeightPredicate(oechem.OEUnaryMolBasePred):
    def __init__(self, minweight, maxweight):
        oechem.OEUnaryMolBasePred.__init__(self)
        self.minweight = minweight
        self.maxweight = maxweight

    def __call__(self, mol):
        weight = oechem.OECalculateMolecularWeight(mol)
        return (weight >= self.minweight and weight <= self.maxweight)

    def CreateCopy(self):
        # __disown__ is required to allow C++ to take ownership of this
        # object and its memory
        return MoleculeWeightPredicate(self.minweight, self.maxweight).__disown__()
# @ </SNIPPET-PREDICATE>


if len(sys.argv) != 2:
    oechem.OEThrow.Usage("%s <ssdatabase>" % sys.argv[0])

dbfname = sys.argv[1]

screentype = oechem.OEGetSubSearchScreenType(oechem.OESubSearchScreenType_SMARTS)

if not oechem.OEIsValidSubSearchDatabase(dbfname, screentype):
    oechem.OEThrow.Fatal("Invalid SMARTS substructure search database file!")

nrthreads = 1
# @ <SNIPPET>
ssdb = oechem.OESubSearchDatabase(dbfname, oechem.OESubSearchDatabaseType_Default, nrthreads)

qmol = oechem.OEQMol()
oechem.OEParseSmarts(qmol, "c1c[n,o]cc1")

maxmatches = 100
query = oechem.OESubSearchQuery(qmol, maxmatches)

result = oechem.OESubSearchResult()
ssdb.Search(result, query)
print("Number of total matches = {}".format(result.NumTotalMatches()))

# search filtered by molecule weight

minweight, maxweight = 200.0, 350.0
query.SetFilter(MoleculeWeightPredicate(minweight, maxweight))

filteredresult = oechem.OESubSearchResult()
ssdb.Search(filteredresult, query)
print("Number of total matches (filtered) = {}".format(filteredresult.NumTotalMatches()))

mol = oechem.OEGraphMol()
for index in filteredresult.GetMatchIndices():
    if ssdb.GetMolecule(mol, index):
        print("weight= {:.3f} {}".format(oechem.OECalculateMolecularWeight(mol), oechem.OEMolToSmiles(mol)))
# @ </SNIPPET>
