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

"""Code snippet for ring perception."""

from openeye import oechem, oedepict

from oecookbook.scripts.ring_perception import atoms_in_same_ring

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CC1CCC23C1C(C(C2)C(C3)CC4CCC5(C4)CCCC5)C(=O)C")
oedepict.OEPrepareDepiction(mol)

width, height = 400, 300
image = oedepict.OEImage(width, height)


class IsSpiroAtom(oechem.OEUnaryAtomPred):
    """
    Predicate class to identify spiro atoms.

    Spiro atoms are the single, central atom that connects more distinct molecular rings.
    """

    def __call__(self, atom: oechem.OEAtomBase) -> bool:
        """Evaluate the atom."""
        spiro_atom_hvy_degree = 4
        if not atom.IsInRing() or atom.GetHvyDegree() != spiro_atom_hvy_degree:
            return False
        ring_neighs = [nbr for nbr in atom.GetAtoms() if nbr.IsInRing()]
        if len(ring_neighs) != spiro_atom_hvy_degree:
            # spiro atom have to have 4 ring neighbors
            return False

        # spiro atom has to have to 2 pairs of neighbors in 2 different rings)
        for neigh in ring_neighs:

            num_neighs_in_same_ring = 0
            for other_neigh in ring_neighs:
                if neigh.GetIdx() == other_neigh.GetIdx():
                    continue
                if atoms_in_same_ring(neigh, other_neigh):
                    num_neighs_in_same_ring += 1
            if num_neighs_in_same_ring != 1:
                #  bridgehead atom not a spiro atom
                return False
        return True


scale = oedepict.OEScale_AutoScale
opts = oedepict.OE2DMolDisplayOptions(width, height, scale)

disp = oedepict.OE2DMolDisplay(mol, opts)
highlight = oedepict.OEHighlightByBallAndStick(oechem.OEBlueTint)
oedepict.OEAddHighlighting(disp, highlight, IsSpiroAtom())
oedepict.OERenderMolecule(image, disp)
oedepict.OEWriteImage("depict_spiro_atoms.svg", image)
