class Formatter(object):
    """ Base Formatter Class """

    def __init__(self, format=None):
        ### Choose either from default functions in FORMATTER_TYPE_MAPPINGS using format_type 
        ### or wriet a function in format_string
        if format:
            if format in FORMATTER_TYPE_MAPPINGS:
                self.formatter = RawJavaScriptText(FORMATTER_TYPE_MAPPINGS[format])
            elif isinstance(format, basestring):
                self.formatter = RawJavaScriptText(format)
            else:
                raise OptionTypeError("Option Type Mismatch: Expected: %s" % basestring)

    def __options__(self):
        return self.formatter

    def __jsonable__(self):
        return self.formatter class Events(CommonObject):
    """ Class for event listener """

    ALLOWED_OPTIONS = {
    "addSeries": (JSfunction, basestring),
    "afterPrint": (JSfunction, basestring),
    "beforePrint": (JSfunction, basestring),
    "click": (JSfunction, basestring),
    "drilldown": (JSfunction, basestring),
    "drillup": (JSfunction, basestring),
    "load": (JSfunction, basestring),
    "redraw": (JSfunction, basestring),
    "selection": (JSfunction, basestring),
    "afterAnimate": (JSfunction, basestring),
    "checkboxClick": (JSfunction, basestring),
    "hide": (JSfunction, basestring),
    "legendItemClick": (JSfunction, basestring),
    "mouseOut": (JSfunction, basestring),
    "mouseOver": (JSfunction, basestring),
    "show": (JSfunction, basestring),
    "remove": (JSfunction, basestring),
    "select": (JSfunction, basestring),
    "unselect": (JSfunction, basestring),
    "update": (JSfunction, basestring),
    "afterBreaks": (JSfunction, basestring),
    "afterSetExtremes": (JSfunction, basestring),
    "pointBreak": (JSfunction, basestring),
    "setExtremes": (JSfunction, basestring)  
    } class Position(CommonObject):
    ALLOWED_OPTIONS = {
    "align": basestring,
    "verticalAlign": basestring,
    "x": int,
    "y": int, 
    } class ContextButton(CommonObject):
    """ Option class for the export button """
    ALLOWED_OPTIONS = {
    "align": basestring,
    "alignTo": basestring,
    "enabled": bool,
    "height": int,
    "menuItems": NotImplemented,
    "onclick": (JSfunction, basestring),
    "style": (CSSObject, dict),
    "symbol": basestring,
    "symbolFill": basestring,
    "symbolSize": int,
    "symbolStroke": basestring,
    "symbolStrokeWidth": int,
    "symbolX": [float, int],
    "symbolY": [float, int],
    "text": basestring,
    "theme": NotImplemented,#ThemeObject
    "verticalAlign": basestring,
    "width": int,
    "x": int,
    "y": int, 
    } class Options3d(CommonObject): 
    ALLOWED_OPTIONS = {
    "alpha": [float, int],
    "beta": [float, int],
    "depth": int,
    "enabled": bool,
    "frame": NotImplemented, # FrameObject
    "viewDistance": int
    } class ResetZoomButton(CommonObject): 
    ALLOWED_OPTIONS = {
    "position": (Position, dict),
    "relativeTo": basestring,
    "theme": NotImplemented #ThemeObject
    } class DrillUpButton(CommonObject): 
    ALLOWED_OPTIONS = {
    "position": (Position, dict),
    "relativeTo": basestring,
    "theme": NotImplemented #ThemeObject
    } class Labels(CommonObject):   
    ALLOWED_OPTIONS = {
    "align": basestring,
    "backgroundColor": (ColorObject, basestring, dict),
    "borderColor": (ColorObject, basestring, dict),
    "borderRadius": [float, int],
    "borderWidth": [int, float, basestring],
    "color": (ColorObject, basestring, dict),
    "connectorColor": (ColorObject, basestring, dict),
    "connectorPadding": [float, int],
    "connectorWidth": [float, int],
    "crop": bool,
    "defer": bool,
    "distance": int,
    "enabled": bool,
    "format": [basestring, type(None)],
    "formatter": (Formatter, JSfunction, basestring),
    "inside": bool,
    "overflow": basestring,
    "padding": [float, int],
    "rotation": int, 
    "shadow": [bool, dict], #shadow object
    "shape": basestring,
    "softConnector": bool,
    "staggerLines": int,
    "step": int,
    "style": (CSSObject, dict),
    "text": basestring,
    "textAlign": basestring,
    "useHTML": bool,
    "verticalAlign": basestring,
    "x": int,
    "y": int,
    "zIndex": int,
    } class Marker(CommonObject):
    ALLOWED_OPTIONS = {
    "enabled": bool,
    "fillColor": (ColorObject, basestring, dict),
    "height": int,
    "lineWidth": int,
    "lineColor": (ColorObject, basestring, dict),
    "radius": int,
    "states": (States, dict),
    "symbol": basestring,
    "width": int
    } class Point(CommonObject):
    ALLOWED_OPTIONS = {
    "events": Events
    } class States(CommonObject):
    ALLOWED_OPTIONS = {
    "hover": dict,
    "select": dict,
    } class Tooltip(CommonObject):
    ALLOWED_OPTIONS = {
    "dateTimeLabelFormats": (DateTimeLabelFormats, dict),
    "followPointer": bool,
    "followTouchMove": bool,
    "footerFormat": basestring,
    "headerFormat": basestring,
    "hideDelay": int,
    "pointFormat": basestring,
    "pointFormatter": (Formatter, JSfunction, basestring),
    "shape": basestring,
    "valueDecimals": int,
    "valuePrefix": basestring,
    "valueSuffix": basestring,
    "xDateFormat": basestring
    } class Title(CommonObject): 
    ALLOWED_OPTIONS = {
    "align": basestring,
    "enabled": bool,
    "margin": int,
    "offset": int,
    "rotation": int,
    "style": (CSSObject, dict),
    "text": [basestring, type(None)]
    } class JSfunction(object):

    def __init__(self, function = None):
        if function:
            if isinstance(function, basestring):
                self.function = RawJavaScriptText(function)
            elif isinstance(function, JSfunction):
                self.function = function
            else:
                raise OptionTypeError("Option Type Mismatch: Expected: %s" % basestring)

    def __options__(self):
        return self.function

    def __jsonable__(self):
        return self.function class MapObject(object):
    """ Base Map Class """

    def __init__(self, mapdata=None):
        if mapdata:
            if isinstance(mapdata, basestring):
                self.map = RawJavaScriptText(mapdata)
            elif isinstance(mapdata, JSfunction):
                self.map = mapdata
            else:
                raise OptionTypeError("Option Type Mismatch: Expected: %s" % basestring)

    def __options__(self):
        return self.map

    def __jsonable__(self):
        return self.map class ColorObject(object):
    """ color object """
    
    def __init__(self, color=None, **kwargs):
        if not color:
            color = kwargs
        
        if color:
            if isinstance(color, dict):
                tmp = []            
                for i, item in enumerate(color['stops']):
                    tmp.append([RawJavaScriptText(x) if isinstance(x, basestring) and any([REGEX_LIST[key].search(x) for key in REGEX_LIST.keys()]) 
                                else x for x in item ])
                color['stops'] = tmp
                self.color = color
            elif any([REGEX_LIST[key].search(color) for key in REGEX_LIST.keys()]):
                self.color = RawJavaScriptText(color)
            elif isinstance(color, basestring):
                self.color = color
            else:
                raise OptionTypeError("Option Type Mismatch: Expected: %s" % (basestring or dict))
        else:
            self.color = None

    def __options__(self):
        return self.color

    def __jsonable__(self):
        return self.color class CSSObject(object):
    """ CSS style class """

    def __init__(self, **kwargs):
        self.css = kwargs

        for k, v in self.css.items():
            if isinstance(v, basestring) and any([REGEX_LIST[key].search(v) for key in REGEX_LIST.keys()]):
                v = RawJavaScriptText(v)
                self.css.update({k:v})

    def __options__(self):
        return self.css

    def __jsonable__(self):
        return self.css class SVGObject(object):
    """ SVG style class """

    def __init__(self, **kwargs):
        self.svg = kwargs

        for k, v in self.svg.items():
            if isinstance(v, basestring) and any([REGEX_LIST[key].search(v) for key in REGEX_LIST.keys()]):
                v = RawJavaScriptText(v)
                self.svg.update({k:v})
    
    def __options__(self):
        return self.svg

    def __jsonable__(self):
        return self.svg class CommonObject(object):

    def __init__(self, **kwargs):
        self.process_kwargs(kwargs)

    def __validate_options__(self, k,v,ov):

        if ov == NotImplemented: 
            raise OptionTypeError("Option Type Currently Not Supported: %s" % k)
        if isinstance(ov,list):
            if isinstance(v,tuple(ov)): return True
            else:
                raise OptionTypeError("Option Type Currently Not Supported: %s" % k)
        else:
            if ov == NotImplemented: raise OptionTypeError("Option Type Currently Not Supported: %s" % k)
            if isinstance(v,ov): return True
            else: return False

    def __options__(self):
        return self.__dict__

    def __jsonable__(self):
        return self.__dict__

    def update(self, kwargs):
        for k, v in kwargs.items(): 
            if k in self.ALLOWED_OPTIONS:
                if isinstance(self.ALLOWED_OPTIONS[k], tuple) and isinstance(self.ALLOWED_OPTIONS[k][0](), CommonObject):
                    # re-construct input dict with existing options in objects
                    if self.__getattr__(k):
                        if isinstance(v, dict):
                            self.__options__()[k].update(v)
                        else:
                            self.__options__()[k].__options__().update(v)
                    else:
                        self.__options__().update({k:allowed_args[k][0](**v)}) 

                elif isinstance(self.ALLOWED_OPTIONS[k], tuple) and isinstance(self.ALLOWED_OPTIONS[k][0](), ArrayObject):
                    # update array 
                    if isinstance(v, dict):
                        self.__dict__[k].append(self.ALLOWED_OPTIONS[k][0](**v))
                    elif isinstance(v, list):
                        for item in v:
                            self.__dict__[k].append(self.ALLOWED_OPTIONS[k][0](**item))
                    else:
                        OptionTypeError("Not An Accepted Input Type: %s" % type(v))        

                elif isinstance(self.ALLOWED_OPTIONS[k], tuple) and \
                    (isinstance(self.ALLOWED_OPTIONS[k][0](), CSSObject) or isinstance(self.ALLOWED_OPTIONS[k][0](), SVGObject)):
                    if self.__getattr__(k):
                        for key, value in v.items():
                            self.__dict__[k].__options__().update({key:value})
                    else:
                        self.__dict__.update({k:allowed_args[k][0](**v)})
                    
                    v = self.__dict__[k].__options__()
                    # upating object
                    if isinstance(v, dict):
                        self.__dict__.update({k:self.ALLOWED_OPTIONS[k][0](**v)})
                    else:
                        self.__dict__.update({k:self.ALLOWED_OPTIONS[k][0](v)})

                elif isinstance(self.ALLOWED_OPTIONS[k], tuple) and (isinstance(self.ALLOWED_OPTIONS[k][0](), JSfunction) or \
                    isinstance(self.ALLOWED_OPTIONS[k][0](), Formatter) or isinstance(self.ALLOWED_OPTIONS[k][0](), ColorObject)):
                    if isinstance(v, dict):
                        self.__dict__.update({k:self.ALLOWED_OPTIONS[k][0](**v)})
                    else:
                        self.__dict__.update({k:self.ALLOWED_OPTIONS[k][0](v)})
                else:
                    self.__dict__.update({k:v})

            else:
                raise OptionTypeError("Not An Accepted Option Type: %s" % k)

    def process_kwargs(self,kwargs):
        
        for k, v in kwargs.items():
            if k in self.ALLOWED_OPTIONS:
                if self.__validate_options__(k,v,self.ALLOWED_OPTIONS[k]):
                    if isinstance(self.ALLOWED_OPTIONS[k], tuple) and \
                        self.ALLOWED_OPTIONS[k][0] in IDV_OBJECT_LIST:
                        if isinstance(v, dict):
                            self.__dict__.update({k:self.ALLOWED_OPTIONS[k][0](**v)})
                        elif isinstance(v, CommonObject) or isinstance(v, ArrayObject) or \
                            isinstance(v, CSSObject) or isinstance(v, SVGObject) or isinstance(v, ColorObject) or \
                            isinstance(v, JSfunction) or isinstance(v, Formatter) or isinstance(v, datetime.datetime):
                            self.__dict__.update({k:v})
                        else:
                            self.__dict__.update({k:self.ALLOWED_OPTIONS[k][0](v)})
                    else:
                        self.__dict__.update({k:v})
                else:
                    raise OptionTypeError("Option Type Mismatch: Expected: %s" % self.ALLOWED_OPTIONS[k])
            else:
                raise OptionTypeError("Option: %s Not Allowed For CommonObject:" % k) class ArrayObject(object):

    def __init__(self, **kwargs):
        self.data = []
        self.process_kwargs(kwargs)

    def __validate_options__(self, k,v,ov):
 
        if ov == NotImplemented: 
            raise OptionTypeError("Option Type Currently Not Supported: %s" % k)
        if isinstance(ov,list):
            if isinstance(v,tuple(ov)): return True
            else:
                raise OptionTypeError("Option Type Currently Not Supported: %s" % k)
        else:
            if ov == NotImplemented: raise OptionTypeError("Option Type Currently Not Supported: %s" % k)
            if isinstance(v,ov): return True
            else: return False

    def __options__(self):
        return self.data

    def __jsonable__(self):
        return self.data

    def update(self, kwargs):
        self.process_kwargs(kwargs)

    def process_kwargs(self,kwargs):
        temp = {}
        for k, v in kwargs.items():
            if k in self.ALLOWED_OPTIONS:
                if self.__validate_options__(k,v,self.ALLOWED_OPTIONS[k]):
                    if isinstance(self.ALLOWED_OPTIONS[k], tuple) and \
                        self.ALLOWED_OPTIONS[k][0] in IDV_OBJECT_LIST:
                        if isinstance(v, dict):
                            temp.update({k:self.ALLOWED_OPTIONS[k][0](**v)})
                        elif isinstance(v, CommonObject) or isinstance(v, ArrayObject) or \
                            isinstance(v, CSSObject) or isinstance(v, SVGObject) or isinstance(v, ColorObject) or \
                            isinstance(v, JSfunction) or isinstance(v, Formatter) or isinstance(v, datetime.datetime):
                            temp.update({k:v})
                        else:
                            temp.update({k:self.ALLOWED_OPTIONS[k][0](v)})
                    else:
                        temp.update({k:v})   
                else: 
                    raise OptionTypeError("Option Type Mismatch: Expected: %s" % self.ALLOWED_OPTIONS[k])
            else: 
                raise OptionTypeError("Option: %s Not Allowed For ArrayObject:" % k)
        self.data.append(temp)
from past.builtins import basestring
from .common import Formatter, Events, Position, ContextButton, Options3d, ResetZoomButton, DrillUpButton, Labels, \
    Marker, Point, States, Tooltip, Title, JSfunction, MapObject, ColorObject, CSSObject, SVGObject, \
    CommonObject, ArrayObject
import json, datetime
    "name": basestring,
    "path": basestring,
    "value": [int, float, list],
    "x": [int, float],
    "y": [int, float],
    "z": [float, int],
    "xAxis": int,
    "yAxis": int,
}

DEFAULT_OPTIONS = {

}

class OptionTypeError(Exception):

    def __init__(self, *args):
        self.args = args


class SeriesOptions(object):
    """Class for plotOptions"""

    def __init__(self, series_type="map", supress_errors=False, **kwargs):
        self.load_defaults(series_type)
        self.process_kwargs(kwargs, series_type=series_type, supress_errors=supress_errors)

    @staticmethod
    def __validate_options__(k, v, ov):
        if isinstance(ov,list):
            if isinstance(v,tuple(ov)): return True
            else:
                raise OptionTypeError("Option Type Currently Not Supported: %s" % k)
        else:
          if ov == NotImplemented: raise OptionTypeError("Option Type Currently Not Supported: %s" % k)
          if isinstance(v,ov): return True
          else: return False

    def __options__(self):
        return self.__dict__

    def __jsonable__(self):
        return self.__dict__

    def __display_options__(self):
        print(json.dumps(self.__options__(),indent=4,sort_keys=True))

    def update(self,series_type, **kwargs):
        allowed_args = PLOT_OPTION_ALLOWED_ARGS[series_type]
        allowed_args.update(PLOT_OPTION_ALLOWED_ARGS["common"])

        for k, v in kwargs.items():
            if k in allowed_args:
                if SeriesOptions.__validate_options__(k,v,allowed_args[k]):
                    if isinstance(allowed_args[k], tuple) and isinstance(allowed_args[k][0](), CommonObject):
                        # re-construct input dict with existing options in objects
                        if self.__getattr__(k):
                            if isinstance(v, dict):
                                self.__options__()[k].update(v)
                            else:
                                self.__options__()[k].__options__().update(v)
                        else:
                            self.__options__().update({k:allowed_args[k][0](**v)}) 

                    elif isinstance(allowed_args[k], tuple) and isinstance(allowed_args[k][0](), ArrayObject):
                        # update array 
                        if isinstance(v, dict):
                            self.__dict__[k].append(allowed_args[k][0](**v))
                        elif isinstance(v, list):
                            for item in v:
                                self.__dict__[k].append(allowed_args[k][0](**item))
                        else:
                            OptionTypeError("Not An Accepted Input Type: %s" % type(v))        

                    elif isinstance(allowed_args[k], tuple) and \
                        (isinstance(allowed_args[k][0](), CSSObject) or isinstance(allowed_args[k][0](), SVGObject)):
                        if self.__getattr__(k):
                            for key, value in v.items():
                                self.__dict__[k].__options__().update({key:value})
                        else:
                            self.__dict__.update({k:allowed_args[k][0](**v)})
                        
                        v = self.__dict__[k].__options__()
                        # upating object
                        if isinstance(v, dict):
                            self.__dict__.update({k:allowed_args[k][0](**v)})
                        else:
                            self.__dict__.update({k:allowed_args[k][0](v)})

                    elif isinstance(allowed_args[k], tuple) and (isinstance(allowed_args[k][0](), JSfunction) or \
                        isinstance(allowed_args[k][0](), Formatter) or isinstance(allowed_args[k][0](), ColorObject)):
                        if isinstance(v, dict):
                            self.__dict__.update({k:allowed_args[k][0](**v)})
                        else:
                            self.__dict__.update({k:allowed_args[k][0](v)})
                    else:
                        self.__dict__.update({k:v})
            else: 
                print(k,v)
                if not supress_errors: raise OptionTypeError("Option Type Mismatch: Expected: %s" % allowed_args[k])
                

    def process_kwargs(self, kwargs, series_type, supress_errors=False):
        allowed_args = PLOT_OPTION_ALLOWED_ARGS[series_type]
        allowed_args.update(PLOT_OPTION_ALLOWED_ARGS["common"])

        for k, v in kwargs.items():
            if k in allowed_args:
                if SeriesOptions.__validate_options__(k,v,allowed_args[k]):
                    if isinstance(allowed_args[k], tuple):
                        if isinstance(v, dict):
                            self.__dict__.update({k:allowed_args[k][0](**v)})
                        elif isinstance(v, list):
                            if len(v) == 1:
                                self.__dict__.update({k:allowed_args[k][0](**v[0])})
                            else:
                                self.__dict__.update({k:allowed_args[k][0](**v[0])})
                                for item in v[1:]:
                                    self.__dict__[k].update(item)
                        elif isinstance(v, CommonObject) or isinstance(v, ArrayObject) or \

                            isinstance(v, CSSObject) or isinstance(v, SVGObject) or isinstance(v, ColorObject) or \