# -*- coding: utf-8 -*-
"""
Created on Thu Mar  5 10:43:56 2026
@author: Nicolas Tharaud
          __  
    ___  |_|____ ___
  / __ \/ / ___/ __ \
 / / / / / |__| |_| |
/_/ /_/_/\___/\____/T
"""

from matplotlib.colors import LinearSegmentedColormap
from .loader import load_hex
import importlib.resources as pkg_resources
import numpy as np
import matplotlib.pyplot as plt

# --- Palette as a list of HEX colors
def pal_hex(name):
    return load_hex(name)

# --- Palette as a matplotlib colormap
def pal(name, N=256, reverse=False):
    colors = load_hex(name)
    if reverse:
        colors = colors[::-1]
    return LinearSegmentedColormap.from_list(name, colors, N=N)

# --- List of Nicopal available
def pal_list():
    files = pkg_resources.contents("nicopal.data")
    palettes = set()
    for f in files:
        if f.endswith("_hex.json"):
            name = f.split("_")[1]   
            palettes.add(name)
    return sorted(list(palettes))

# --- Visualize a palette
def pal_show(name, N=256):
    colmap = pal(name, N)
    gradient = np.linspace(0,1,N).reshape(1,-1)
    plt.figure(figsize=(6,1))
    plt.imshow(gradient, aspect="auto", cmap=colmap)
    plt.axis("off")
    plt.title(name)
    plt.show()
    
# --- Visualize all palettes
def pal_gallery(N=256, ncols=4, reverse=False):
    palettes = pal_list()
    n = len(palettes)
    nrows = int(np.ceil(n / ncols))
    fig, axes = plt.subplots(nrows, ncols, figsize=(3*ncols, 1.2*nrows))
    gradient = np.linspace(0, 1, N).reshape(1, -1)
    axes = np.array(axes).reshape(-1)
    for ax, p in zip(axes, palettes):
        colmap = pal(p, N=N, reverse=reverse)
        ax.imshow(gradient, aspect="auto", cmap=colmap)
        ax.set_axis_off()
        ax.set_title(p, fontsize=10)
    for ax in axes[len(palettes):]:
        ax.axis("off")
    plt.tight_layout()
    plt.show()
    
def pal_all():
    pal_gallery()
    
    
# --- Palette valid
def pal_test():
    for p in pal_list():
        assert len(pal_hex(p)) > 0, f"Palette {p} empty"
    print("All palettes are valid!")
    
# --- Return n discrete colors
def pal_sample(name, n, reverse=False):
    colmap = pal(name, N=n, reverse=reverse)
    return [colmap(i/(n-1)) for i in range(n)]

# --- Show a demo plot
def pal_demo(name, size=30):
    data = np.random.rand(size, size)
    plt.figure(figsize=(5,4))
    im = plt.imshow(data, cmap=pal(name))
    plt.colorbar(im)
    plt.title(f"Nicopal demo: {name}")
    plt.axis("off")
    plt.show()