import os

import sys

__author__ = 'bakl'

ROOT_DIRECTORY = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
plugin_path = os.path.join(ROOT_DIRECTORY, 'plugin')


def lc_wrapper(param, p=None, method='plot'):
    a = param.split(':')
    fname = a.pop(0)
    if p is None:
        if os.path.isfile(fname + '.py'):
            p, fname = os.path.split(fname)
        elif os.path.isfile(os.path.join(os.getcwd(), fname + '.py')):
            p = os.getcwd()
        else:
            p = plugin_path
    # print("Call: {} from {}".format(fname, p))
    c = CallBack(fname, path=p, args=a, method=method, load=1)
    print("Call: %s from %s" % (c.Func, c.FuncFileFull))
    return c


def observations(args):
    """
    Get observations from argument line
    :param args: argument line parsed with argparse.ArgumentParser
    :return: data from callbacks
    """
    if not args.call or len(args.call) == 0:
        return None

    if len(args.call) == 1:
        callback = lc_wrapper(args.call[0], method='load')
    else:  # len(args.call) > 1
        a = []
        for line in args.call:
            c = lc_wrapper(line, method='load')
            a.append(c)
        callback = CallBackArray(a)

    if callback is None:
        return None

    # Get observations
    obs = callback.run({'is_debug': args.is_not_quiet})
    return obs


class CallBack(object):
    def __init__(self, fname, path='./', args=None, method=None, load=1):
        self._func = None
        self._path = path
        self._fname = fname
        self._args = args
        if fname is not None and load == 1:
            if method is None:
                self._func = self.find_func
            else:
                self._func = self.find_method(method)

    @property
    def Path(self):
        return self._path

    @property
    def FileName(self):
        return self._fname

    @property
    def FuncFile(self):
        return self.FileName + '.py'

    @property
    def FuncFileFull(self):
        return os.path.join(self.Path, self.FuncFile)

    @property
    def Func(self):
        return self._func

    def get_arg(self, idx):
        if self._args is None:
            return None
        if len(self._args) > idx:
            return self._args[idx]
        return None

    def set_arg(self, idx, val):
        if idx < 0: