from matplotlib.lines import Line2D
from matplotlib.legend_handler import HandlerTuple


# --- Handler custom pour dessiner point + barre verticale ---
class HandlerErrorBar(HandlerTuple):
    def create_artists(self, legend, orig_handle, xdescent, ydescent,
                       width, height, fontsize, trans):
        artists = []
        # Décalage horizontal pour chaque handle
        n = len(orig_handle)
        spacing = (width+5) / (n+1)
        for i, h in enumerate(orig_handle):
            if h is None:
                continue  # on saute les None
            # position x spécifique pour ce handle
            x = xdescent + spacing*(i+1)
            y = ydescent + height/2
            # point
            marker = Line2D([x], [y], marker=h.get_marker(), color=h.get_color(),
                            markersize=4, linestyle='', transform=trans,
                            alpha=h.get_alpha())
            # barre verticale
            bar = Line2D([x, x], [y-6, y+6], color=h.get_color(),
                         transform=trans, alpha=h.get_alpha())
            # caps horizontaux
            # cap1 = Line2D([x-3, x+3], [y+6, y+6], color=h.get_color(), transform=trans)
            # cap2 = Line2D([x-3, x+3], [y-6, y-6], color=h.get_color(), transform=trans)
            artists.extend([marker, bar]) #, cap1, cap2])
        return artists
class HandlerErrorBarbicol(HandlerTuple):
    def create_artists(self, legend, orig_handle, xdescent, ydescent,
                       width, height, fontsize, trans):
        artists = []
        # Décalage horizontal pour chaque handle
        n = len(orig_handle)
        spacing = (width+5) / (n+1)
        for i, h in enumerate(orig_handle):
            if h is None:
                continue  # on saute les None
            # position x spécifique pour ce handle
            x = xdescent + spacing*(i+1)
            y = ydescent + height/2
            
            # barre verticale
            bar = Line2D([x, x], [y-6, y+6], color=h.get_markeredgecolor(),
                         transform=trans, alpha=h.get_alpha(), zorder=2)
 
            # point
            marker = Line2D([x], [y], marker=h.get_marker(), color=h.get_markerfacecolor(),
                            markersize=4, linestyle='', transform=trans,
                            alpha=h.get_alpha(), zorder=3)
           # caps horizontaux
            # cap1 = Line2D([x-3, x+3], [y+6, y+6], color=h.get_color(), transform=trans)
            # cap2 = Line2D([x-3, x+3], [y-6, y-6], color=h.get_color(), transform=trans)
            artists.extend([bar,marker]) #, cap1, cap2])
        return artists

