# coding=utf-8
"""
Management of modelio macros.
"""

import logging
log = logging.getLogger(__name__)

import os

import xml.etree.ElementTree as ElementTree


class MacroCatalog(object):
    def __init__(self, scope, catalogFile):

        def __parseMacroCatalogAndRegisterMacros(catalogFile):
            catalog = ElementTree.parse(catalogFile).getroot()
            if catalog.tag != 'catalog':
                raise EnvironmentError(
                    'The file %s does not seems to be a valid macro catalog'
                    % self.catalogFile
                )
            for script in catalog:
                a = script.attrib
                show_in_menu = True if a['show-menu']=='true' else False
                show_in_tool_bar = \
                    True if a['show-toolbar'] == 'true' else False
                try:
                    description=script.find('description').text
                except AttributeError:
                    description=''
                metaclassNames = []
                for metaclass in script.iter('metaclass'):
                    metaclassNames.append(metaclass.get('name'))
                macro = Macro(
                    catalog=self,
                    label=a['name'],
                    macroFile=a['path'],
                    metaclassNames=metaclassNames,
                    description=description,
                    icon=a['icon-path'],
                    showInMenu=show_in_menu,
                    showInToolBar=show_in_tool_bar
                    )
        self.scope = scope
        self.catalogFile = catalogFile
        self.macroDirectory = os.path.basename(self.catalogFile)
        self.macros = []
        __parseMacroCatalogAndRegisterMacros(self.catalogFile)


class Macro(object):
    def __init__(self, catalog,
                 label, macroFile,
                 metaclassNames=(),
                 description='',
                 icon='', showInMenu=True, showInToolBar=True):
        # register the macro to the catalog
        self.catalog = catalog
        self.catalog.macros.append(self)

        self.label = label
        self.macroFile = macroFile
        self.metaclassNames = metaclassNames
        self.description = description
        self.icon = icon
        self.showInMenu = showInMenu
        self.showInToolBar = showInToolBar


class PluginMacro(Macro):
    def __init__(self, catalog, label, plugin, function, modules, postCode='',
                 metaclassNames=(),
                 description='',
                 icon='', showInMenu=True, showInToolBar=True):
        macro_file = 'plugin_'+plugin+'_'+function+'.py'
        super(PluginMacro, self).__init__(
            catalog = catalog,
            label=label, macroFile=macro_file,
            metaclassNames = metaclassNames,
            description=description,
            icon=icon, showInMenu=showInMenu, showInToolBar=showInToolBar
        )
        self.plugin = plugin
        self.function = function
        self.modules = modules
        self.postCode = postCode


    def generateMacroFile(self):
        full_filename = \
            os.path.join(self.catalog.macroDirectory, self.macroFile)
        print '-'*80
        print full_filename
        print '-'*80
        print PLUGIN_MACRO_TEMPLATE.format(
            modules=self.modules,
            postCode=self.postCode,
        )


PLUGIN_MACRO_TEMPLATE = """
# Do not put some encoding here
# This file is automatically generated by PyModelio.
# DO NO CHANGE IT unless you know what you are doing.
DEBUG=True

# pymodelio startup (will check if some action is required)
import os
execfile( os.path.join(os.path.expanduser("~"),
          ".modelio","pymodelio_startup.py"))

modules={modules}
from pymodelio.core.env import PyModelioEnv
PyModelioEnv.execute({pluginLower},modules,DEBUG)
{postCode}

"""



