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


#############################################################################
# Depicts molecule with fragment highlights
#############################################################################

import sys
from openeye import oechem
from openeye import oedepict
from openeye import oemedchem


def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureImageWidth(itf, 400.0)
    oedepict.OEConfigureImageHeight(itf, 300.0)
    oedepict.OEConfigure2DMolDisplayOptions(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    iname = itf.GetString("-in")
    oname = itf.GetString("-out")

    # check input/output files

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    # initialize fragmentation function

    fragfunc = get_fragmentation_function(itf)

    # read a molecule

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

    # create image

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
    image = oedepict.OEImage(width, height)

    # setup depiction options

    opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(opts, itf)
    opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome)

    # depict molecule with fragment highlights

    oedepict.OEPrepareDepiction(mol)
    depict_molecule_with_fragment_highlights(image, mol, fragfunc, opts)

    oedepict.OEWriteImage(ofs, ext, image)

    return 0


def depict_molecule_with_fragment_highlights(image, mol, fragfunc, opts):

    fraglist = [f for f in fragfunc(mol)]
    nrfrags = len(fraglist)

    colorg = oechem.OELinearColorGradient()
    colorg.AddStop(oechem.OEColorStop(0, oechem.OEMediumYellow))
    colorg.AddStop(oechem.OEColorStop(nrfrags, oechem.OEDarkBrown))

    disp = oedepict.OE2DMolDisplay(mol, opts)

    highlight = oedepict.OEHighlightByLasso(oechem.OEWhite)
    highlight.SetConsiderAtomLabelBoundingBox(True)

    for fidx, frag in enumerate(fraglist):
        highlight.SetColor(colorg.GetColorAt(fidx))
        oedepict.OEAddHighlighting(disp, highlight, frag)

    oedepict.OERenderMolecule(image, disp)


def get_fragmentation_function(itf):

    fstring = itf.GetString("-fragtype")
    if fstring == "funcgroup":
        return oemedchem.OEGetFuncGroupFragments
    if fstring == "ring-chain":
        return oemedchem.OEGetRingChainFragments
    return oemedchem.OEGetRingLinkerSideChainFragments


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


InterfaceData = '''
!CATEGORY "input/output options"
    !PARAMETER -in
      !ALIAS -i
      !TYPE string
      !REQUIRED true
      !KEYLESS 1
      !VISIBILITY simple
      !BRIEF Input filename
    !END

    !PARAMETER -out
      !ALIAS -o
      !TYPE string
      !REQUIRED true
      !KEYLESS 2
      !VISIBILITY simple
      !BRIEF Output filename
    !END
!END

!CATEGORY "fragmentation options"
    !PARAMETER -fragtype
      !ALIAS -ftype
      !TYPE string
      !REQUIRED false
      !KEYLESS 3
      !DEFAULT funcgroup
      !LEGAL_VALUE funcgroup
      !LEGAL_VALUE ring-chain
      !LEGAL_VALUE ring-linker-sidechain
      !VISIBILITY simple
      !BRIEF Fragmentation type
    !END
!END
'''


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