# Path: shmaplib/logger.py
# def getlog():
#     """Get the global log setup by the __main__ script"""
# 
#     if LogData.log_instance is None:
#         setuplog()
# 
#     return LogData.log_instance
# 
# Path: shmaplib/appdata.py
# class Shortcut(object):
#     def __init__(self, name, key, mods=list(), anymod=False):
#         self.name = name
#         self.key = key
#         self.mods = mods
#         self.anymod = anymod
# 
#     def serialize(self):
#         mods = list(set(self.mods))
#         mods.sort()
#         mods_str = json.dumps(mods)
# 
#         return '{"name":"%s", "mods":%s}' % (self.name, mods_str)
# 
#     def __str__(self):
#         return self.serialize()
# 
# class ApplicationConfig(object):
#     def __init__(self, app_name, app_version, app_os, default_context_name):
#         super(ApplicationConfig, self).__init__()
#         self.name = app_name
#         self.version = app_version
#         self.os = app_os
#         self.default_context_name = default_context_name
#         self.contexts = {}
# 
#     def get_or_create_new_context(self, name):
#         """Gets an existing context by name, or adds a new one to the application"""
# 
#         if name in self.contexts.keys():
#             return self.contexts[name]
# 
#         context = ShortcutContext(name)
#         self.contexts[context.name] = context
#         return context
# 
#     def get_mods_used(self):
#         mods_used = []
#         for context in self.contexts.values():
#             for shortcut in context.shortcuts:
#                 for mod in shortcut.mods:
#                     if mod not in mods_used:
#                         mods_used.append(mod)
#         return sorted(mods_used)
# 
#     def is_empty(self):
#         """Returns true if all contexts are empty or AppConfig has no contexts"""
#         for context in self.contexts.values():
#             if len(context.shortcuts) > 0:
#                 return False
#         return True
# 
#     def serialize(self, output_dir):
#         """Serialize this class into a .json file with name: 'APP-NAME_VERSION_OS.json'
#         Returns True for succes, False for failure"""
# 
#         assert os.path.isdir(output_dir), "The output dir is not a directory"
#         assert self.os in VALID_OS_NAMES, "The application Operating system must be one of these: " + str(VALID_OS_NAMES)
#         assert self.version is not None and len(self.version) > 0, "The application version must be assigned"
# 
#         # Check for empty
#         if self.is_empty():
#             log.warn("Cannot export ApplicationConfig because it is empty")
#             return False
# 
#         # todo: handle colons in name
#         appname_for_file = self.name.lower().replace(' ', '-')
#         output_path = os.path.join(output_dir, "{0}_{1}_{2}.json".format(appname_for_file, self.version, self.os).lower())
#         log.info('serializing ApplicationConfig to %s', output_path)
# 
#         mods_used = self.get_mods_used()
# 
#         output_str = u'{\n'
#         output_str += u'    "name" : "%s",\n' % self.name
#         output_str += u'    "version" : "%s",\n' % self.version
#         output_str += u'    "os" : "%s",\n' % self.os
#         output_str += u'    "mods_used" : %s,\n' % json.dumps(mods_used)
#         output_str += u'    "default_context" : "%s",\n' % self.default_context_name
#         output_str += u'    "contexts" : {\n'
# 
#         contexts_str = u""
# 
#         contexts = list(self.contexts.values())
#         contexts.sort(key=lambda c: c.name)
#         for context in contexts:
#             # don't serialize empty contexts
#             if len(context.shortcuts) == 0:
#                 continue
# 
#             ctx_str = u'        ' + context.serialize()
#             ctx_str = ctx_str.replace(u'\n', u'\n        ')
# 
#             contexts_str += ctx_str + u',\n'
#         contexts_str = contexts_str.rstrip(u',\n')
# 
#         output_str += contexts_str + u'\n'
#         output_str += u'    }\n'
#         output_str += u'}\n'
# 
#         # Write to file
#         f = codecs.open(output_path, encoding='utf-8', mode='w+')
#         f.write(output_str)
#         f.close()
# 
#         # Regenerate apps.js file, this file has a list of all application json files
#         #  so the web application knows what apps exist
#         regenerate_site_apps_js()
# 
# Path: shmaplib/constants.py
# DIR_CONTENT_GENERATED = os.path.normpath(os.path.join(DIR_ROOT, "content", "generated"))
# 
# VALID_OS_NAMES = [OS_WINDOWS, OS_MAC, OS_LINUX]
# 
# OS_WINDOWS = 'windows'
# 
# OS_MAC = 'mac'


import os
import json
import codecs
import re
from .logger import getlog
from .appdata import Shortcut, ApplicationConfig
from .constants import DIR_CONTENT_GENERATED, VALID_OS_NAMES, OS_WINDOWS, OS_MAC

        json_str += "}\n"

        f = codecs.open(output_filepath, encoding='utf-8', mode='w+')
        f.write(json_str)
        f.close()


class IntermediateDataExporter(object):
    """Exports an intermediate .json file to the contents/generated directory in the correct file format."""

    def __init__(self, source, explicit_numpad_mode=False):
        super(IntermediateDataExporter, self).__init__()
        assert os.path.exists(source), "Source file '%s' does not exist" % source

        self.explicit_numpad_mode = explicit_numpad_mode

        # Load intermediate data
        self.idata = IntermediateShortcutData()
        self.idata.load(source)

        # Get app prefs from intermediate data format
        self.app_name = self.idata.name
        self.app_version = self.idata.version
        self.default_context_name = self.idata.default_context

        # Windows and Mac app configs
        self.data_windows = None
        self.data_mac = None
        if OS_WINDOWS in self.idata.os:

# Path: shmaplib/logger.py
# def getlog():
#     """Get the global log setup by the __main__ script"""
# 
#     if LogData.log_instance is None:
#         setuplog()
# 
#     return LogData.log_instance
# 
# Path: shmaplib/appdata.py
# class Shortcut(object):
#     def __init__(self, name, key, mods=list(), anymod=False):
#         self.name = name
#         self.key = key
#         self.mods = mods
#         self.anymod = anymod
# 
#     def serialize(self):
#         mods = list(set(self.mods))
#         mods.sort()
#         mods_str = json.dumps(mods)
# 
#         return '{"name":"%s", "mods":%s}' % (self.name, mods_str)
# 
#     def __str__(self):
#         return self.serialize()
# 
# class ApplicationConfig(object):
#     def __init__(self, app_name, app_version, app_os, default_context_name):
#         super(ApplicationConfig, self).__init__()
#         self.name = app_name
#         self.version = app_version
#         self.os = app_os
#         self.default_context_name = default_context_name
#         self.contexts = {}
# 
#     def get_or_create_new_context(self, name):
#         """Gets an existing context by name, or adds a new one to the application"""
# 
#         if name in self.contexts.keys():
#             return self.contexts[name]
# 
#         context = ShortcutContext(name)
#         self.contexts[context.name] = context
#         return context
# 
#     def get_mods_used(self):
#         mods_used = []
#         for context in self.contexts.values():
#             for shortcut in context.shortcuts:
#                 for mod in shortcut.mods:
#                     if mod not in mods_used:
#                         mods_used.append(mod)
#         return sorted(mods_used)
# 
#     def is_empty(self):
#         """Returns true if all contexts are empty or AppConfig has no contexts"""
#         for context in self.contexts.values():
#             if len(context.shortcuts) > 0:
#                 return False
#         return True
# 
#     def serialize(self, output_dir):
#         """Serialize this class into a .json file with name: 'APP-NAME_VERSION_OS.json'
#         Returns True for succes, False for failure"""
# 
#         assert os.path.isdir(output_dir), "The output dir is not a directory"
#         assert self.os in VALID_OS_NAMES, "The application Operating system must be one of these: " + str(VALID_OS_NAMES)
#         assert self.version is not None and len(self.version) > 0, "The application version must be assigned"
# 
#         # Check for empty
#         if self.is_empty():
#             log.warn("Cannot export ApplicationConfig because it is empty")
#             return False
# 
#         # todo: handle colons in name
#         appname_for_file = self.name.lower().replace(' ', '-')
#         output_path = os.path.join(output_dir, "{0}_{1}_{2}.json".format(appname_for_file, self.version, self.os).lower())
#         log.info('serializing ApplicationConfig to %s', output_path)
# 
#         mods_used = self.get_mods_used()
# 
#         output_str = u'{\n'
#         output_str += u'    "name" : "%s",\n' % self.name
#         output_str += u'    "version" : "%s",\n' % self.version
#         output_str += u'    "os" : "%s",\n' % self.os
#         output_str += u'    "mods_used" : %s,\n' % json.dumps(mods_used)
#         output_str += u'    "default_context" : "%s",\n' % self.default_context_name
#         output_str += u'    "contexts" : {\n'
# 
#         contexts_str = u""
# 
#         contexts = list(self.contexts.values())
#         contexts.sort(key=lambda c: c.name)
#         for context in contexts:
#             # don't serialize empty contexts
#             if len(context.shortcuts) == 0:
#                 continue
# 
#             ctx_str = u'        ' + context.serialize()
#             ctx_str = ctx_str.replace(u'\n', u'\n        ')
# 
#             contexts_str += ctx_str + u',\n'
#         contexts_str = contexts_str.rstrip(u',\n')
# 
#         output_str += contexts_str + u'\n'
#         output_str += u'    }\n'
#         output_str += u'}\n'
# 
#         # Write to file
#         f = codecs.open(output_path, encoding='utf-8', mode='w+')
#         f.write(output_str)
#         f.close()
# 
#         # Regenerate apps.js file, this file has a list of all application json files
#         #  so the web application knows what apps exist
#         regenerate_site_apps_js()
# 
# Path: shmaplib/constants.py
# DIR_CONTENT_GENERATED = os.path.normpath(os.path.join(DIR_ROOT, "content", "generated"))
# 
# VALID_OS_NAMES = [OS_WINDOWS, OS_MAC, OS_LINUX]
# 
# OS_WINDOWS = 'windows'
# 
# OS_MAC = 'mac'


# Path: shmaplib/intermediate.py
import os
import json
import codecs
import re
from .logger import getlog
from .appdata import Shortcut, ApplicationConfig
from .constants import DIR_CONTENT_GENERATED, VALID_OS_NAMES, OS_WINDOWS, OS_MAC


        json_str += "}\n"

        f = codecs.open(output_filepath, encoding='utf-8', mode='w+')
        f.write(json_str)
        f.close()


class IntermediateDataExporter(object):
    """Exports an intermediate .json file to the contents/generated directory in the correct file format."""

    def __init__(self, source, explicit_numpad_mode=False):
        super(IntermediateDataExporter, self).__init__()
        assert os.path.exists(source), "Source file '%s' does not exist" % source

        self.explicit_numpad_mode = explicit_numpad_mode

        # Load intermediate data
        self.idata = IntermediateShortcutData()
        self.idata.load(source)

        # Get app prefs from intermediate data format
        self.app_name = self.idata.name
        self.app_version = self.idata.version
        self.default_context_name = self.idata.default_context

        # Windows and Mac app configs
        self.data_windows = None
        self.data_mac = None
        if OS_WINDOWS in self.idata.os:

            self.data_windows = ApplicationConfig(self.app_name, self.app_version, OS_WINDOWS, self.default_context_name)