# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# Copyright 2012-2014 Canonical, Ltd.
# Author: Thomi Richards
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.

import logging
import sys


logging.basicConfig()
logger = logging.getLogger(__name__)

def create_qt4_plugin(data):
    from windowmocker.plugins.qt4 import QtPlugin as Qt4Plugin
    return Qt4Plugin(data)

def create_qt5_plugin(data):
    from windowmocker.plugins.qt5 import QtPlugin as Qt5Plugin
    return Qt5Plugin(data)

_plugin_registry = {
    'Qt4': create_qt4_plugin,
    'Qt5': create_qt5_plugin,
}

_default_plugin = create_qt4_plugin

def get_plugin_by_name(name):
    """Return the application type plugin class by name."""
    global _plugin_registry
    plugin = _plugin_registry.get(name, None)
    if not plugin:
        logger.error("No plugin was found with name '%s'", name)
    return plugin

def get_default_plugin_name():
    return 'Qt4'

def get_registered_plugin_names():
    """Get a list of registered plugin names."""
    global _plugin_registry
    if sys.version_info[0] < 3:
        del _plugin_registry['Qt5']
    return _plugin_registry.keys()


def register_named_plugin(plugin_name, plugin_class):
    global _plugin_registry

    old_plugin = _plugin_registry.get(plugin_name, None)
    if old_plugin:
        logger.warning("Plugin %r is already registered with name '%s'. Overwriting it with %r.",
            old_plugin, plugin_name, plugin_class)

    _plugin_registry[plugin_name] = plugin_class

def register_plugin(plugin_class):
    """Register plugin_class. Probably not ever needed, except by tests.

    This function is deprecated and may be removed in a future release.
    Use `register_named_plugin` instead."""
    global _plugin_registry

    old_plugin = _plugin_registry.get(plugin_class.Name, None)
    if old_plugin:
        logger.warning("Plugin %r is already registered with name '%s'. Overwriting it with %r.",
            old_plugin, plugin_class.Name, plugin_class)

    _plugin_registry[plugin_class.Name] = plugin_class

def unregister_plugin_by_name(name):
    """Unregister a plugin with a given name. Probably not ever needed, except by tests."""
    global _plugin_registry

    if name not in _plugin_registry:
        logger.error("Cannot unregister plugin '%s' since it's not already registered.",
            name)
    else:
        _plugin_registry.pop(name)
