#!/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 oemedchem
import sys


################################################################
# USED TO GENERATE CODE SNIPPETS FOR THE OEMEDCHEM DOCUMENTATION
# - please look at actual examples for useful utility code
################################################################


def SerializeInput(itf):
    ims = oechem.oemolistream()
    if not ims.open(itf.GetString("-input")):
        oechem.OEThrow.Fatal("Unable to open %s for reading:"+itf.GetString("-input"))

    oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Warning)

    # @ <SNIPPET-MATCHEDPAIRANALYZER-EXPORT-COMPRESS-MMP>
    # create analyzer class with defaults
    #   - compression option disabled by default
    mmpAnalyzer = oemedchem.OEMatchedPairAnalyzer()
    # for serialization, enable export compression to
    #   remove singleton index nodes by modifying analyzer
    mmpAnalyzer.ModifyOptions(oemedchem.OEMatchedPairOptions_ExportCompression, 0)
    # @ </SNIPPET-MATCHEDPAIRANALYZER-EXPORT-COMPRESS-MMP>

    # @ <SNIPPET-MATCHEDPAIRANALYZER-EXPORT-COMPRESS-OPTS>
    # create options class with defaults
    #   - compression option disabled by default
    mmpOpts = oemedchem.OEMatchedPairAnalyzerOptions()
    # for serialization, enable export compression to
    #   remove singleton index nodes by modifying analyzer
    mmpOpts.SetOptions(oemedchem.OEMatchedPairOptions_Default |
                       oemedchem.OEMatchedPairOptions_ExportCompression)
    # create analyzer class with compression option enabled
    mmpAnalyzer = oemedchem.OEMatchedPairAnalyzer(mmpOpts)
    # @ </SNIPPET-MATCHEDPAIRANALYZER-EXPORT-COMPRESS-OPTS>

    # @ <SNIPPET-MATCHEDPAIRANALYZER-SERIALIZE-INDEX>
    mmp = oemedchem.OEMatchedPairAnalyzer()
    for recindex, mol in enumerate(ims.GetOEGraphMols()):
        status = mmp.AddMol(mol, recindex)
        if status != recindex:
            oechem.OEThrow.Warning(
                "{0}: molecule indexing error, status={1}"
                .format(recindex, oemedchem.OEMatchedPairIndexStatusName(status)))

    print("Index complete, matched pairs = {0}".format(mmp.NumMatchedPairs()))

    # check for output filename with .mmpidx extension
    mmpexport = itf.GetString("-output")
    if not oemedchem.OEIsMatchedPairAnalyzerFileType(mmpexport):
        oechem.OEThrow.Info('Not a valid matched pair index output file, '+mmpexport)
    elif not oemedchem.OEWriteMatchedPairAnalyzer(mmpexport, mmp):
        oechem.OEThrow.Fatal("Index serialization failed")
    else:
        oechem.OEThrow.Info("Index serialization complete")
    # @ </SNIPPET-MATCHEDPAIRANALYZER-SERIALIZE-INDEX>
    print("Index serialization complete")

    mmpimport = mmpexport
    # now try to reload serialized index
    # @ <SNIPPET-MATCHEDPAIRANALYZER-DESERIALIZE-INDEX>
    mmp = oemedchem.OEMatchedPairAnalyzer()
    if not oemedchem.OEIsMatchedPairAnalyzerFileType(mmpimport):
        oechem.OEThrow.Fatal('Not a valid matched pair index input file, '+mmpimport)
    elif not oemedchem.OEReadMatchedPairAnalyzer(mmpimport, mmp):
        oechem.OEThrow.Fatal("Index deserialization failed")
    else:
        oechem.OEThrow.Info("Index deserialization complete")
    # @ </SNIPPET-MATCHEDPAIRANALYZER-DESERIALIZE-INDEX>
    print("Index deserialization complete")

    return True


############################################################
InterfaceData = """
# SerializeIndex docexample
!CATEGORY SerializeIndex
    !CATEGORY I/O
        !PARAMETER -input 1
          !ALIAS -i
          !TYPE string
          !REQUIRED true
          !BRIEF Input filename of structures to index
          !KEYLESS 1
        !END

        !PARAMETER -output 2
          !ALIAS -o
          !TYPE string
          !REQUIRED true
          !BRIEF Output filename for serialized index
          !KEYLESS 2
        !END
    !END
!END
"""


def main(argv=[__name__]):
    itf = oechem.OEInterface(InterfaceData)
    oemedchem.OEConfigureMatchedPairIndexOptions(itf)

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

    SerializeInput(itf)


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