"""Internal functions used by messages module"""

import os


def format_message(message):
    """Simple formatting of messages in message python files"""
    return message.strip()


def load_messages(directory):
    """Load messages from directory as dictionary
    
    Iterate over all python files in a directory, read them as python modules,
    get MESSAGES variable from each file and merge all that into a single
    result dictionary.  Python files that end with '_custom.py' has more
    priority.
    """
    built_in_messages = dict()

    # Messages customized by end users of the hosting check library or
    # migration tools. They are located in "*_custom.py" files. Such messages
    # override built in ones. Custom files are nesessary so auto upgrade could
    # never rewrite changed files
    custom_messages = dict()

    messages_dir = os.path.join(os.path.dirname(__file__), directory)
    for module_file in os.listdir(messages_dir):
        if (
            not module_file.endswith('.py') or
            module_file.endswith('__init__.py')
        ):
            continue
        full_module_name = ".".join([
            ".".join(['parallels.hosting_check.messages'] + directory.split('/')),
            module_file[:-3]
        ])
        module = __import__(
            full_module_name,
            globals(), locals(), ['MESSAGES']
        )
        if hasattr(module, 'MESSAGES'):
            if not module_file.endswith('_custom.py'):
                built_in_messages.update(module.MESSAGES)
            else:
                custom_messages.update(module.MESSAGES)

    all_messages = dict(built_in_messages)
    all_messages.update(custom_messages)
    return all_messages
