# Copyright (C) <Year>  <Name>
# All rights reserved.

# ~~~~~~~~~~~~ localimport bootstrap ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# see https://gist.github.com/NiklasRosenstein/f5690d8f36bbdc8e5556
import os, sys, glob
class localimport(object):
    _modulecache = []
    _eggs = staticmethod(lambda x: glob.glob(os.path.join(x, '*.egg')))
    def __init__(self, libpath, autoeggs=False, foreclosed=False, path=os.path):
        if not path.isabs(libpath):
            libpath = path.join(path.dirname(path.abspath(__file__)), libpath)
        self.libpath = libpath; self.autoeggs = autoeggs; self.fclosed = foreclosed
    def __enter__(self):
        self._path, self._mpath = list(sys.path), list(sys.meta_path)
        self._mods = frozenset(sys.modules.keys())
        sys.path.append(self.libpath)
        sys.path.extend(self._eggs(self.libpath) if self.autoeggs else [])
    def __exit__(self, *args):
        sys.path[:] = self._path; sys.meta_path[:] = self._mpath
        for key in sys.modules.keys():
            if key not in self._mods and self._islocal(sys.modules[key]):
                localimport._modulecache.append(sys.modules.pop(key))
    def _islocal(self, mod):
        if self.fclosed: return True
        filename = getattr(mod, '__file__', None)
        if filename:
            try: s = os.path.relpath(filename, self.libpath)
            except ValueError: return False
            else: return s == os.curdir or not s.startswith(os.pardir)
        else: return False
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

import c4d
with localimport('libs'):
    pass

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Plugin Implementation
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

def register_command(cls):
    """
    Registers a Cinema 4D CommandData plugin. The class object
    passed here must have several attributes, optional ones marked
    with a star (\*).

    - PLUGIN_ID
    - PLUGIN_NAME
    - PLUGIN_INFO \*
    - PLUGIN_ICON \* *(must be c4d.bitmaps.BaseBitmap)
    - PLUGIN_HELP \*

    :return: The created and registered instance of the command.
    """

    import weakref
    info = getattr(cls, 'PLUGIN_INFO', c4d.PLUGINFLAG_COMMAND_HOTKEY)
    icon = getattr(cls, 'PLUGIN_ICON', None)
    help = getattr(cls, 'PLUGIN_HELP', '')

    instance = cls()
    success = c4d.plugins.RegisterCommandPlugin(
        cls.PLUGIN_ID, cls.PLUGIN_NAME, info, icon, help, instance)
    return instance if success else None

class PluginCommand(c4d.plugins.CommandData):

    PLUGIN_ID = 1000010 # Test ID Only
    PLUGIN_NAME = 'Plugin Name'

    # c4d.plugins.CommandData

    def Execute(self, doc):
        return True

    def RestoreLayout(self, secret):
        return True

def main():
    register_command(PluginCommand)

if __name__ == '__main__':
    main()

