from sys        import modules
from os.path    import dirname, join, realpath
from ...objects import fragment, fragbio

# YL 03/09/2020: we have to wrap the current module using a dummy class to use the "special method",
#                namely __XXX__(), because before Python 3.7 they are only available in classes. See:
#                https://stackoverflow.com/questions/2447353
#                and
#                http://mail.python.org/pipermail/python-ideas/2012-May/014969.html


class __Ligands(object):
    '''A wrapper class to disguise the current module'''

    selectcases = { 'co' : 'co.pun',
                    'co2': 'co2.pun',
                    'no' : 'no.pdb',
#                    'no2': 'no2.pun',
                    'o2' : 'o2.pdb',
                    'oo' : 'o2.pdb',
                  }


    def __init__(self, wrapped):
        ''''''

        self.wrapped = wrapped

    
    def __getattr__(self, ligand):
        '''Load the fragment only when accessed'''
    
    #    if hasattr(self, ligand.lower()):
    #        return 
    
        if ligand.lower() in self.selectcases.keys():
            frag = fragbio.FragmentBio(coords=join(dirname(__file__), self.selectcases[ligand.lower()]))
            setattr(self, ligand.lower(), frag)

            return frag
    
        else:
            if not ligand.startswith('__') and not ligand.endswith('__'):
                print(" >>> ERROR: the specified ligand \"{}\" is not available".format(ligand.lower()))
                self.avail
            return None


    @property
    def avail(self):
        ''''''

        print("\n Available built-in ligands are:\n {}".format(list(self.selectcases.keys())))


modules[__name__] = __Ligands(modules[__name__])
