#!/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>
from openeye import oechem
from threading import Thread
try:
    from queue import Queue
except ImportError:
    from Queue import Queue
import sys

ss = oechem.OESubSearch(sys.argv[1])

ifs = oechem.oemolithread(sys.argv[2])
ofs = oechem.oemolothread(sys.argv[3])

iqueue = Queue(1024)
oqueue = Queue(1024)


class ParseThread(Thread):
    def run(self):
        mol = oechem.OEGraphMol()
        while oechem.OEReadMolecule(ifs, mol):
            iqueue.put(mol, block=True)
            mol = oechem.OEGraphMol()

        # signal SearchThread to die
        iqueue.put(None, block=True)


class SearchThread(Thread):
    def run(self):
        mol = iqueue.get(block=True)
        while mol is not None:
            oechem.OEPrepareSearch(mol, ss)
            if ss.SingleMatch(mol):
                oqueue.put(mol, block=True)

            mol = iqueue.get(block=True)

        # signal main thread to die
        oqueue.put(None, block=True)


pthrd = ParseThread()
pthrd.start()

sthrd = SearchThread()
sthrd.start()

# main thread will handle output
mol = oqueue.get(block=True)
while mol is not None:
    oechem.OEWriteMolecule(ofs, mol)
    mol = oqueue.get(block=True)
# @ </SNIPPET>
