'''
Created on 06.01.2014

@author: afedynitch
'''

def set_ticks(n_divs=5):
    from matplotlib.pyplot import gca
    from matplotlib.ticker import AutoMinorLocator
    ax = gca()
    ax.yaxis.set_minor_locator(AutoMinorLocator(n_divs))
    ax.xaxis.set_minor_locator(AutoMinorLocator(n_divs))
       
def set_ticks_x(n_divs=5):
    from matplotlib.pyplot import gca
    from matplotlib.ticker import AutoMinorLocator
    ax = gca()
    ax.xaxis.set_minor_locator(AutoMinorLocator(n_divs))
    
def set_ticks_y(n_divs=5):
    from matplotlib.pyplot import gca
    from matplotlib.ticker import AutoMinorLocator
    ax = gca()
    ax.yaxis.set_minor_locator(AutoMinorLocator(n_divs))
    
def cornertext(text, loc=2, color=None, frameon=False,
               axes=None, **kwargs):
    """
    Conveniently places text in a corner of a plot.
    
    Parameters
    ----------
    text: string or tuple of strings
      Text to be placed in the plot. May be a tuple of strings to get
      several lines of text.
    loc: integer or string
      Location of text, same as in legend(...).
    frameon: boolean (optional)
      Whether to draw a border around the text. Default is False.
    axes: Axes (optional, default: None)
      Axes object which houses the text (defaults to the current axes).
    fontproperties: matplotlib.font_manager.FontProperties object
      Change the font style.
    
    Other keyword arguments are forwarded to the text instance.
    
    Authors
    -------
    Hans Dembinski <hans.dembinski@kit.edu>
    """
    
    from matplotlib.offsetbox import AnchoredOffsetbox, VPacker, TextArea
    from matplotlib import rcParams
    from matplotlib.font_manager import FontProperties
    import warnings
    
    if axes is None:
        from matplotlib import pyplot as plt
        axes = plt.gca()
    
    locTranslate = {
      'upper right'  : 1,
      'upper left'   : 2,
      'lower left'   : 3,
      'lower right'  : 4,
      'right'        : 5,
      'center left'  : 6,
      'center right' : 7,
      'lower center' : 8,
      'upper center' : 9,
      'center'       : 10
    }
    
    if isinstance(loc, str):
        if loc in locTranslate:
            loc = locTranslate[loc]
        else :
            message = 'Unrecognized location "%s". Falling back on "upper left"; valid locations are\n\t%s' \
                      % (loc, '\n\t'.join(locTranslate.keys()))
            warnings.warn(message)
            loc = 2
    
    if "borderpad" in kwargs:
        borderpad = kwargs["borderpad"]
    else:
        borderpad = rcParams["legend.borderpad"]
    
    if "borderaxespad" in kwargs:
        borderaxespad = kwargs["borderaxespad"]
    else:
        borderaxespad = rcParams["legend.borderaxespad"]
    
    if "handletextpad" in kwargs:
        handletextpad = kwargs["handletextpad"]
    else:
        handletextpad = rcParams["legend.handletextpad"]
    
    if "fontproperties" in kwargs:
        fontproperties = kwargs["fontproperties"]  # @UnusedVariable
        del kwargs["fontproperties"]
    else:
        if "size" in kwargs:
            size = kwargs["size"]
            del kwargs["size"]
        elif "fontsize" in kwargs:
            size = kwargs["fontsize"]
            del kwargs["fontsize"]
        else:
            size = rcParams["legend.fontsize"]
    fontproperties = FontProperties(size=size)
    
    texts = [text] if isinstance(text, str) else text
    
    colors = [ color for t in texts ] if (isinstance(color, str) or color is None) else color
    
    tas = []
    for t, c in zip(texts, colors):
        ta = TextArea(t,
                    textprops={"color":c, "fontproperties":fontproperties},
                    multilinebaseline=True,
                    minimumdescent=True,
                    **kwargs)
        tas.append(ta)
    
    vpack = VPacker(children=tas, pad=0, sep=handletextpad)
    
    aob = AnchoredOffsetbox(loc, child=vpack,
                            pad=borderpad,
                            borderpad=borderaxespad,
                            frameon=frameon)
    
    axes.add_artist(aob)
    return aob

def plot_hist(xedges, ws, axes=None, facecolor=None, **kwargs):
    """Plots histogram data in ROOT style.

    Parameters
    ----------
    xedge: lower bin boundaries + upper boundary of last bin
    w: content of the bins
    """
 
    if axes is None:
        from matplotlib import pyplot as plt
        axes = plt.gca()

    import numpy as np

    m = len(ws)
    n = 2 * m + 2

    xs = np.zeros(n)
    ys = np.zeros(n)

    xs[0] = xedges[0]
    xs[-1] = xedges[-1]

    for i in xrange(m):
        xs[1 + 2 * i] = xedges[i]
        ys[1 + 2 * i] = ws[i]
        xs[1 + 2 * i + 1] = xedges[i + 1]
        ys[1 + 2 * i + 1] = ws[i]

    if not facecolor is None:
        return axes.fill(xs, ys, facecolor=facecolor, **kwargs)
    else:
        return axes.plot(xs, ys, **kwargs)

def _get_closest(value, in_list):
    import numpy as np
    """Returns the closes value to 'value' from given list.
        """
    minindex = np.argmin(np.abs(in_list - value * np.ones(len(in_list))))
    return minindex, in_list[minindex]

def get_bins_and_width_from_centers(vector):
    import numpy as np
    vector_log = np.log10(vector)
    steps = vector_log[1] - vector_log[0]
    bins_log = vector_log - 0.5 * steps
    bins_log = np.resize(bins_log, vector_log.size + 1)
    bins_log[-1] = vector_log[-1] + 0.5 * steps
    bins = 10 ** bins_log
    widths = bins[1:] - bins[:-1]
    return bins, widths