# -*- coding: utf-8 -*-
#------------------------------------------------------------
# smytvshow
# Plugin command dispatcher
# http://smystero.dlinkddns.org/smytvshow/
#------------------------------------------------------------

from xbmcutils import logger
import urlparse
import items
import param

def run_action(target_type, target, action, caller_item):
    ret = None
    try:
        target_package = get_package(target_type)
        target_module = __import__("%s.%s" % (target_package, target), fromlist=["%s" % target_package])

        if hasattr(target_module, "__class_name__"):
            try:
                class_name = target_module.__class_name__

                if hasattr(target_module, class_name):
                    try:
                        class_ = getattr(target_module, class_name)
                        instance = class_()
                        if hasattr(instance, action):
                            try:
                                ret = getattr(instance, action)(caller_item)

                            except Exception as e:
                                logger.error("Class [%s] has not a method called [%s]. [%s]" % (class_name, action, e.message))

                                import traceback,sys
                                exc_type, exc_value, exc_tb = sys.exc_info()
                                lines = traceback.format_exception(exc_type, exc_value, exc_tb)
                                for line in lines:
                                    line_splits = line.split("\n")
                                    for line_split in line_splits:
                                        logger.error(line_split)

                    except AttributeError as e:
                        logger.error("Target [%s] doesn't define a class called [%s]. [%s]" % (class_name, e.message))

            except AttributeError as e:
                logger.error("Target [%s] doesn't define [class_name]. [%s]" % (target,  action,e.message))

    except ImportError as e:
        logger.error("Import [%s.%s] failed [%s]." % (target_package, target, e.message))

    return ret

def get_package(type):
    ret = ""

    if type == "I":
        ret = ""
    elif type == "M":
        ret = "menus"
    elif type == "P":
        ret = "pushers"

    return ret


def item_to_callerItem(item):
    url = item.build_url()
    pos = url.find("?") + 1
    url = url[pos:]
    ci = param.Param(urlparse.parse_qs(url)).get_caller_item()
    return ci
