#!/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.

#############################################################################
# Calculates the polar surface area of a set molecules and visualize them on
# the molecule surfaces
#############################################################################

import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme

from psa_utils import SetAtomProperties
from psa_utils import PSAArcFxn


def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigure2DMolDisplayOptions(itf, oedepict.OE2DMolDisplaySetup_AromaticStyle)
    oedepict.OEConfigureReportOptions(itf)

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

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

    pagebypage = itf.GetBool("-pagebypage")

    # 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 pagebypage and not oedepict.OEIsRegisteredMultiPageImageFile(ext):
        oechem.OEThrow.Warning("Report will be generated into separate pages!")
        pagebypage = True

    # initialize multi-page report

    ropts = oedepict.OEReportOptions()
    oedepict.OESetupReportOptions(ropts, itf)
    report = oedepict.OEReport(ropts)

    # setup depiction options

    width, height = report.GetCellWidth(), report.GetCellHeight()
    opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(opts, itf)

    # read molecules and prepare them for depiction

    mollist = []
    for mol in ifs.GetOEGraphMols():
        oedepict.OEPrepareDepiction(mol)
        mollist.append(oechem.OEGraphMol(mol))

    # depict molecule with XLogP atom contributions

    DepictMoleculesWithPSA(report, mollist, opts)

    if pagebypage:
        oedepict.OEWriteReportPageByPage(oname, report)
    else:
        oedepict.OEWriteReport(oname, report)

    return 0


def DepictMoleculesWithPSA(report, mollist, opts):

    molscale = float("inf")
    for mol in mollist:
        molscale = min(molscale, oegrapheme.OEGetMoleculeSurfaceScale(mol, opts))
    opts.SetScale(molscale)

    tag = oechem.OEGetTag("PSA")

    minvalue = float("inf")
    maxvalue = float("-inf")
    for mol in mollist:
        minvalue, maxvalue = SetAtomProperties(mol, tag, minvalue, maxvalue, True)

    ncolor = oechem.OEColorStop(minvalue, oechem.OEWhite)
    pcolor = oechem.OEColorStop(maxvalue, oechem.OEDarkBlue)
    colorg = oechem.OELinearColorGradient(ncolor, pcolor)

    arcfxn = PSAArcFxn(colorg, tag, opts.GetDefaultBondPen())

    for mol in mollist:

        for atom in mol.GetAtoms():
            oegrapheme.OESetSurfaceArcFxn(mol, atom, arcfxn)

        disp = oedepict.OE2DMolDisplay(mol, opts)
        oegrapheme.OEDraw2DSurface(disp)

        cell = report.NewCell()
        oedepict.OERenderMolecule(cell, disp)


InterfaceData = '''
!CATEGORY "input/output options"

    !PARAMETER -in
      !ALIAS -i
      !TYPE string
      !REQUIRED true
      !KEYLESS 1
      !VISIBILITY simple
      !BRIEF Input filename(s)
    !END

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

!END

!CATEGORY "report options"

    !PARAMETER -pagebypage
      !ALIAS -p
      !TYPE bool
      !REQUIRED false
      !DEFAULT false
      !VISIBILITY simple
      !BRIEF Write individual numbered separate pages
    !END

!END
'''

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