"""The "Givre" skin of WinZik: frosted ice and glass. A pale blue-white case with a fine frost grain and frost ferns in
its corners, glossy translucent buttons (a white sheen on their top half, a soft glow at the bottom), dark navy LCDs
with ice-blue digits and thin silver outlines. Drawn from scratch, pixel by pixel (no picture copied, no logo).
Run (from the winzik-jumphp folder): python3 -I apps/winzik/tools/skins/givre.py apps/winzik/assets/skins/givre
"""
import math
import os
import random
import sys
from PIL import Image, ImageDraw, ImageFont

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import pixelfont  # noqa: E402

OUT = sys.argv[1] if len(sys.argv) > 1 else 'assets/skins/givre'
os.makedirs(OUT, exist_ok=True)

CASE_TOP = (238, 245, 252)
CASE_BOTTOM = (204, 221, 239)
SILVER = (146, 163, 188)
SILVER_DARK = (112, 130, 160)
WHITE = (255, 255, 255)
NAVY_TOP = (22, 38, 72)
NAVY_BOTTOM = (9, 17, 40)
NAVY_GRID = (26, 46, 82)
ICE = (150, 214, 255)
ICE_DIM = (98, 150, 205)
INK = (30, 52, 96)
GLASS_TOP = (222, 236, 250)
GLASS_BOTTOM = (164, 196, 232)
S = 4                                                   # supersampling of the glass pieces


FONTS = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'assets', 'fonts')


def font(size, bold=True):
    """The app's own font (ui-bold.ttf / ui.ttf), else Pillow's."""
    try:
        return ImageFont.truetype(os.path.join(FONTS, 'ui-bold.ttf' if bold else 'ui.ttf'), size)
    except OSError:
        try:
            return ImageFont.load_default(size=size)
        except TypeError:
            return ImageFont.load_default()


def new(w, h, color=(0, 0, 0, 0)):
    return Image.new('RGBA', (w, h), color)


def save(im, name):
    im.save(os.path.join(OUT, name + '.png'))


def mix(a, b, t):
    return tuple(int(round(a[i] * (1 - t) + b[i] * t)) for i in range(len(a)))


def text(d, xy, s, size=8, fill=INK, anchor='la', bold=True):
    if size <= 8:
        # small texts: a pixel font (whole pixels, sharp: an anti-aliased TTF blurs at this size)
        pixelfont.draw(d._image, (int(xy[0]), int(xy[1])), s.upper(), fill, pixelfont.F5 if size >= 7 else pixelfont.F3, anchor)
        return
    d.fontmode = 'L'
    d.text(xy, s, font=font(size, bold), fill=fill, anchor=anchor)


# --- the case: a vertical gradient, a frost grain, sparkles, frost ferns ----------------------------------------------
def case(w, h, seed, calm=None):
    """calm = (y0, y1): rows left without grain (the band of the play list that is stretched)."""
    rnd = random.Random(seed)
    im = new(w, h, CASE_TOP + (255,))
    px = im.load()
    for y in range(h):
        base = mix(CASE_TOP, CASE_BOTTOM, y / max(1, h - 1))
        quiet = calm is not None and calm[0] <= y < calm[1]
        for x in range(w):
            if quiet:
                px[x, y] = base + (255,)
                continue
            n = rnd.randint(-3, 3)
            c = tuple(max(0, min(255, base[i] + n + (1 if i == 2 else 0))) for i in range(3))
            if rnd.random() < 0.012:
                c = mix(c, WHITE, 0.8)                  # a frost sparkle
            px[x, y] = c + (255,)
    return im


def fern(im, x, y, angle, length, depth, seed, alpha=110):
    """A frost fern: a stem with short side branches, each branching again (drawn in white, translucent)."""
    rnd = random.Random(seed)
    layer = new(im.width, im.height)
    d = ImageDraw.Draw(layer)

    def branch(x0, y0, a, l, n):
        if l < 2 or n < 0:
            return
        x1 = x0 + math.cos(a) * l
        y1 = y0 + math.sin(a) * l
        d.line([(x0, y0), (x1, y1)], fill=(255, 255, 255, alpha))
        steps = max(2, int(l / 4))
        for i in range(1, steps):
            t = i / steps
            bx, by = x0 + (x1 - x0) * t, y0 + (y1 - y0) * t
            side = l * (1 - t) * 0.45 * (0.8 + rnd.random() * 0.4)
            branch(bx, by, a - 1.0, side, n - 1)
            branch(bx, by, a + 1.0, side, n - 1)

    branch(x, y, angle, length, depth)
    im.alpha_composite(layer)


def outline(d, x0, y0, x1, y1):
    """The case's thin silver edge, a white light inside it."""
    d.rectangle([x0, y0, x1, y1], outline=SILVER)
    d.line([(x0 + 1, y0 + 1), (x1 - 1, y0 + 1)], fill=WHITE)
    d.line([(x0 + 1, y0 + 1), (x0 + 1, y1 - 1)], fill=(248, 252, 255))
    d.line([(x0 + 1, y1 - 1), (x1 - 1, y1 - 1)], fill=(186, 204, 226))
    d.line([(x1 - 1, y0 + 1), (x1 - 1, y1 - 1)], fill=(194, 210, 230))


def lcd(im, x, y, w, h, grid=False, fade=None):
    """A navy window: silver ring around it, a navy gradient, a faint glass reflection on its top."""
    d = ImageDraw.Draw(im)
    d.rectangle([x - 1, y - 1, x + w, y + h], outline=SILVER_DARK)
    d.line([(x - 1, y + h), (x + w, y + h)], fill=WHITE)
    d.line([(x + w, y - 1), (x + w, y + h)], fill=(236, 243, 251))
    for yy in range(y, y + h):
        d.line([(x, yy), (x + w - 1, yy)], fill=mix(NAVY_TOP, NAVY_BOTTOM, min(1, (yy - y) / max(1, (fade or h) - 1))))
    d.line([(x, y), (x + w - 1, y)], fill=(44, 66, 108))
    if grid:
        for gy in range(y + 1, y + h, 2):
            for gx in range(x + 1, x + w, 2):
                d.point((gx, gy), fill=NAVY_GRID)


def groove(d, x0, y0, x1):
    """Two fine silver lines carved in the case (a decoration)."""
    d.line([(x0, y0), (x1, y0)], fill=(176, 192, 214))
    d.line([(x0, y0 + 1), (x1, y0 + 1)], fill=WHITE)


# --- glass: glossy pieces drawn 4 times bigger then reduced (smooth edges) ----------------------------------------
def gradient(w, h, top, bottom):
    g = new(w, h)
    d = ImageDraw.Draw(g)
    for y in range(h):
        d.line([(0, y), (w - 1, y)], fill=mix(top, bottom, y / max(1, h - 1)))
    return g


def glass(w, h, radius=3, top=GLASS_TOP, bottom=GLASS_BOTTOM, edge=SILVER_DARK, draw=None):
    """A candy-glass piece: a cool gradient, a bright sheen on the top half (sharp lower edge), a glow at the bottom.
    draw(d, k) draws the symbol on the big picture (k = the scale)."""
    W, H, R = w * S, h * S, radius * S
    mask = Image.new('L', (W, H), 0)
    ImageDraw.Draw(mask).rounded_rectangle([0, 0, W - 1, H - 1], R, fill=255)
    body = gradient(W, H, top + (255,), bottom + (255,))
    # the sheen: the top half, white fading downwards, its lower edge straight
    sheen = new(W, H)
    sd = ImageDraw.Draw(sheen)
    half = int(H * 0.5)
    for y in range(S, half):
        t = (y - S) / max(1, half - S)
        sd.line([(S, y), (W - 1 - S, y)], fill=(255, 255, 255, int(190 - 110 * t)))
    smask = Image.new('L', (W, H), 0)
    ImageDraw.Draw(smask).rounded_rectangle([S + S // 2, S, W - 1 - S - S // 2, half + R], max(S, R - S), fill=255)
    ImageDraw.Draw(smask).rectangle([0, half, W, H], fill=0)
    sheen.putalpha(Image.composite(sheen.getchannel('A'), Image.new('L', (W, H), 0), smask))
    body.alpha_composite(sheen)
    # the glow at the bottom: light passing through the glass
    glow = new(W, H)
    gd = ImageDraw.Draw(glow)
    for i in range(H - half):
        y = H - 1 - S - i
        if y < half:
            break
        a = int(110 * max(0.0, 1 - i / ((H - half) * 0.8)))
        gd.line([(2 * S, y), (W - 1 - 2 * S, y)], fill=(236, 248, 255, a))
    body.alpha_composite(glow)
    d = ImageDraw.Draw(body, 'RGBA')
    d.rounded_rectangle([0, 0, W - 1, H - 1], R, outline=edge + (255,), width=S)
    d.rounded_rectangle([S, S, W - 1 - S, H - 1 - S], max(S, R - S), outline=(255, 255, 255, 120), width=max(1, S // 2))
    if draw:
        draw(d, S)
    body.putalpha(Image.composite(body.getchannel('A'), Image.new('L', (W, H), 0), mask))
    return body.resize((w, h), Image.LANCZOS)


def glyph(d, kind, cx, cy, color, k):
    """The transport symbols, at the scale k."""
    def P(pts):
        d.polygon([(cx + px * k, cy + py * k) for px, py in pts], fill=color)

    def R(x0, y0, x1, y1):
        d.rectangle([cx + x0 * k, cy + y0 * k, cx + x1 * k - 1, cy + y1 * k - 1], fill=color)

    if kind == 'prev':
        R(-6, -4, -4, 4)
        P([(1, -4), (1, 4), (-4, 0)])
        P([(6, -4), (6, 4), (1, 0)])
    elif kind == 'next':
        P([(-6, -4), (-6, 4), (-1, 0)])
        P([(-1, -4), (-1, 4), (4, 0)])
        R(4, -4, 6, 4)
    elif kind == 'play':
        P([(-3, -5), (-3, 5), (5, 0)])
    elif kind == 'pause':
        R(-4, -4, -1, 4)
        R(1, -4, 4, 4)
    elif kind == 'stop':
        R(-4, -4, 4, 4)
    elif kind == 'eject':
        P([(-5, 1), (5, 1), (0, -5)])
        R(-5, 3, 5, 5)
    elif kind == 'down':
        P([(-4, -2), (4, -2), (0, 3)])
    elif kind == 'chevron':
        P([(-5, -3), (-3, -3), (0, 1), (3, -3), (5, -3), (0, 3)])


def symbol(kind=None, label=None, size=8, color=INK, dy=0):
    """The draw() of glass(): the symbol with a white light under it (engraved in the glass)."""
    def draw(d, k):
        w, h = d.im.size
        cx, cy = w / 2, h / 2 + dy * k
        for off, col in [(k, (255, 255, 255, 170)), (0, color + (255,))]:
            if kind:
                glyph(d, kind, cx, cy + off, col, k)
            if label:
                d.text((cx, cy + off), label, font=font(size * k), fill=col, anchor='mm')
    return draw


def button(w, h, kind=None, label=None, size=8, top=GLASS_TOP, bottom=GLASS_BOTTOM, color=INK, radius=3, dy=0):
    return glass(w, h, radius, top, bottom, draw=symbol(kind, label, size, color, dy))


AQUA_TOP = (206, 246, 255)
AQUA_BOTTOM = (96, 196, 240)                          # a lit button (Hasard on, the list mode)

# --- the player (main.png, 258 x 128: 99 shown, 128 opened) -------------------------------------------------------
main = case(258, 128, 1)
fern(main, 3, 126, -1.05, 26, 3, 11, 70)
fern(main, 254, 97, -2.2, 18, 2, 12, 60)
fern(main, 120, 126, -1.4, 14, 2, 13, 50)
d = ImageDraw.Draw(main)
outline(d, 0, 0, 257, 127)
groove(d, 28, 4, 43)
groove(d, 28, 8, 43)
groove(d, 213, 4, 221)
groove(d, 213, 8, 221)
lcd(main, 47, 1, 163, 12)                         # the scrolling title
lcd(main, 27, 17, 197, 12, grid=True)             # the bargraph
lcd(main, 0, 31, 70, 13)                          # "Volume : xx %"
lcd(main, 112, 31, 32, 13)                        # kbps
lcd(main, 186, 31, 70, 13)                        # "Balance : x %"
lcd(main, 0, 81, 56, 17, grid=True)               # the counter
d = ImageDraw.Draw(main)
text(d, (148, 37), 'kbps', 6, (112, 136, 176), 'lm')
# the socket of the light between the two sliders
d.ellipse([121, 46, 133, 58], fill=(150, 168, 194))
d.ellipse([122, 47, 132, 57], fill=NAVY_BOTTOM)
d.arc([121, 46, 133, 58], 20, 200, fill=WHITE)
# the hidden button that opens the bottom: a small glass key with a chevron
main.alpha_composite(glass(25, 18, 3, draw=symbol('chevron', color=INK)), (232, 76))
# the bottom part: a frost plate with an ice crystal, a small LCD
groove(d, 4, 100, 253)
lcd(main, 126, 106, 126, 17)
d = ImageDraw.Draw(main)
crystal = new(258, 128)
cd = ImageDraw.Draw(crystal)
cx, cy = 22, 114
for i in range(6):
    a = math.pi / 3 * i + math.pi / 6
    x1, y1 = cx + math.cos(a) * 10, cy + math.sin(a) * 10
    cd.line([(cx, cy), (x1, y1)], fill=(110, 150, 200, 255), width=1)
    for t, l in [(0.5, 3), (0.78, 2)]:
        bx, by = cx + math.cos(a) * 10 * t, cy + math.sin(a) * 10 * t
        for s in (-1, 1):
            cd.line([(bx, by), (bx + math.cos(a + s * 0.9) * l, by + math.sin(a + s * 0.9) * l)], fill=(110, 150, 200, 255))
main.alpha_composite(crystal)
d = ImageDraw.Draw(main)
text(d, (40, 110), 'WINZIK', 9, (70, 100, 150), 'lm')
text(d, (41, 120), 'givre', 8, (120, 150, 190), 'lm')
save(main, 'main')

# the buttons of the player
save(button(25, 17, label='H'), 'hd')
save(button(25, 17, label='H', top=AQUA_TOP, bottom=AQUA_BOTTOM), 'he')
save(button(25, 17, label='?'), 'info')
save(button(15, 15, label='_', dy=-2), 'petit')
save(button(17, 15, label='x', dy=-1), 'close')
save(button(17, 15, kind='down'), 'tray')
save(button(17, 15, label='L'), 'lyr')
for name, kind in [('barr', 'prev'), ('bpause', 'pause'), ('bplay', 'play'), ('bstop', 'stop'), ('bav', 'next')]:
    save(button(25, 18, kind), name)
save(button(25, 18, label='PL', size=8), 'bpl')


# the sliders: a navy groove, a frosted light that grows
def track(w, h, light):
    im = new(w, h)
    dd = ImageDraw.Draw(im)
    dd.rounded_rectangle([0, 1, w - 1, h - 2], 3, fill=SILVER_DARK)
    dd.rounded_rectangle([1, 2, w - 2, h - 3], 2, fill=NAVY_BOTTOM)
    for x in range(3, w - 3):
        t = (x - 3) / (w - 7)
        c = light(t)
        dd.line([(x, 4), (x, h - 5)], fill=c)
    dd.line([(2, h - 2), (w - 3, h - 2)], fill=WHITE)
    return im


save(track(116, 10, lambda t: mix((28, 52, 96), (170, 228, 255), t)), 'fbson')
save(track(116, 10, lambda t: mix((28, 52, 96), (190, 236, 255), 1 - abs(t - .5) * 2)), 'fbbal')
pos = track(255, 10, lambda t: (24, 44, 84))
pd = ImageDraw.Draw(pos)
for x in range(8, 250, 12):
    pd.point((x, 4), fill=(70, 110, 160))
save(pos, 'fpos')
for name, top, bottom in [('bson', GLASS_TOP, GLASS_BOTTOM), ('bbal', GLASS_TOP, GLASS_BOTTOM), ('bpos', AQUA_TOP, AQUA_BOTTOM)]:
    def notch(d, k):
        w, h = d.im.size
        d.line([(w / 2, 2 * k), (w / 2, h - 2 * k)], fill=INK + (255,), width=k)
    save(glass(17, 9, 4, top, bottom, draw=notch), name)

# --- the play list (mainpl.png, 258 x 362; the 40 rows above the last 26 are stretched) ------------------------------
BAND = (296, 336)
pl = case(258, 362, 2, calm=(BAND[0] - 6, BAND[1]))
fern(pl, 30, 30, -0.5, 16, 2, 21, 55)
fern(pl, 228, 30, -2.6, 16, 2, 22, 55)
d = ImageDraw.Draw(pl)
outline(d, 0, 0, 257, 361)
groove(d, 28, 5, 84)
groove(d, 28, 10, 84)
groove(d, 174, 5, 228)
groove(d, 174, 10, 228)
groove(d, 28, 22, 116)
groove(d, 149, 22, 228)
# the title plate
lcd(pl, 60, 35, 138, 10)
d = ImageDraw.Draw(pl)
text(d, (129, 40), 'LISTE DE LECTURE', 7, ICE, 'mm')
# the list and its scroll track; the status tab (the number of files) hangs under the list
lcd(pl, 1, 48, 246, 302, fade=60)            # flat below its top: it is stretched or cut
lcd(pl, 249, 48, 8, 297)
d = ImageDraw.Draw(pl)
# the status tab under the list (WinZik writes the number of files there): the list's own navy, opened into it
d.rectangle([45, 347, 212, 360], fill=SILVER_DARK)
d.rectangle([46, 347, 211, 359], fill=NAVY_BOTTOM)
d.line([(46, 360), (212, 360)], fill=WHITE)
d.line([(212, 351), (212, 360)], fill=(236, 243, 251))
# the resize grips: a triangle of frost beads in each bottom corner (the grips are 16 x 12)
for right in (False, True):
    for dx, dy in [(0, 0), (4, 0), (8, 0), (4, -4), (8, -4), (8, -8)]:
        x = 244 + dx if right else 11 - dx
        y = 358 + dy
        d.rectangle([x, y, x + 1, y + 1], fill=SILVER_DARK)
        d.point((x, y), fill=WHITE)
        d.point((x + 2, y + 2), fill=(176, 194, 218))
save(pl, 'mainpl')
for name, label in [('plp', '+'), ('plm', '-'), ('plload', 'L'), ('plsave', 'S')]:
    save(button(25, 17, label=label, size=10), name)


def bin_icon(d, k):
    w, h = d.im.size
    cx, cy = w / 2, h / 2
    for off, col in [(k, (255, 255, 255, 170)), (0, INK + (255,))]:
        d.rectangle([cx - 3 * k, cy - 2 * k + off, cx + 3 * k, cy + 4 * k + off], outline=col, width=k)
        d.line([(cx - 4 * k, cy - 3 * k + off), (cx + 4 * k, cy - 3 * k + off)], fill=col, width=k)
        d.line([(cx - 1 * k, cy - 4 * k + off), (cx + 1 * k, cy - 4 * k + off)], fill=col, width=k)
        d.line([(cx, cy - 1 * k + off), (cx, cy + 3 * k + off)], fill=col, width=k)


save(glass(25, 17, 3, draw=bin_icon), 'plrem')
save(button(82, 16, label='MODE ÉDITION', size=8), 'pledit')
save(button(82, 16, label='MODE LISTE', size=8, top=AQUA_TOP, bottom=AQUA_BOTTOM), 'pledit2')
# the scroll bar: its track and its thumb
trk = new(8, 296, NAVY_BOTTOM + (255,))
td = ImageDraw.Draw(trk)
td.line([(3, 2), (3, 293)], fill=(34, 58, 100))
td.line([(4, 2), (4, 293)], fill=(20, 36, 70))
save(trk, 'posplay')
save(glass(8, 17, 3, AQUA_TOP, AQUA_BOTTOM), 'btnplay')
# the icons of the lines: the kind of file, the lyrics
for name, label, color in [('infomp3', 'MP3', (150, 214, 255)), ('infowav', 'WAV', (160, 240, 220)),
                           ('infomid', 'MID', (200, 180, 255)), ('infocd', 'CD', (220, 230, 240))]:
    im = new(17, 9)
    dd = ImageDraw.Draw(im)
    dd.rounded_rectangle([0, 0, 16, 8], 2, outline=color)
    text(dd, (8.5, 4.5), label, 7, color, 'mm')
    save(im, name)
for name, fill, rim in [('lyrok', (120, 226, 255), WHITE), ('lyrno', (34, 56, 96), (60, 86, 130))]:
    im = new(17 * S, 9 * S)
    dd = ImageDraw.Draw(im)
    dd.ellipse([4 * S, 1 * S, 12 * S, 8 * S], fill=fill + (255,), outline=rim + (255,), width=S // 2)
    if name == 'lyrok':
        dd.ellipse([6 * S, 2 * S, 9 * S, 4 * S], fill=(255, 255, 255, 220))
    save(im.resize((17, 9), Image.LANCZOS), name)

# --- the compact bar (mainp.png, 112 x 12) and its buttons ------------------------------------------------------
mp = case(112, 12, 3)
outline(ImageDraw.Draw(mp), 0, 0, 111, 11)
save(mp, 'mainp')
for name, kind, label in [('arrp', 'prev', None), ('pausep', 'pause', None), ('playp', 'play', None), ('avp', 'next', None),
                          ('petitp', None, '_'), ('helpp', None, '?'), ('lyrp', None, 'L')]:
    def small(d, k, kind=kind, label=label):
        w, h = d.im.size
        cx, cy = w / 2, h / 2
        for off, col in [(k, (255, 255, 255, 170)), (0, INK + (255,))]:
            if kind:
                glyph(d, kind, cx, cy + off, col, k * 0.7)
            if label:
                d.text((cx, cy + off - (2 * k if label == '_' else 0)), label, font=font(8 * k), fill=col, anchor='mm')
    save(glass(17, 13, 3, draw=small), name)

# --- the icon -----------------------------------------------------------------------------------------------------
ico = glass(32, 32, 7)
dd = ImageDraw.Draw(ico)
dd.rectangle([5, 7, 26, 16], fill=NAVY_BOTTOM, outline=SILVER_DARK)
text(dd, (16, 12), 'WZ', 8, ICE, 'mm')
big = new(32 * S, 32 * S)
glyph(ImageDraw.Draw(big), 'play', 16 * S, 23 * S, INK + (255,), S)
ico.alpha_composite(big.resize((32, 32), Image.LANCZOS))
save(ico, 'ico')


# --- INFO.txt: the colours, as VB wrote them (&H00BBGGRR&) -------------------------------------------------------
def vb(rgb):
    r, g, b = rgb
    return '&H00%02X%02X%02X&' % (b, g, r)


colors = [(176, 226, 255),                                           # title
          (140, 200, 245), (140, 200, 245), (140, 200, 245),         # volume, balance, kbps
          (205, 240, 255), (205, 240, 255), (205, 240, 255),         # hours, minutes, seconds
          (96, 186, 250), (96, 186, 250),                            # the bargraph: ice blue,
          (215, 240, 255), (215, 240, 255),                          # frost white,
          (255, 120, 150), (255, 120, 150),                          # then a cold red
          (255, 255, 255)]                                           # the line playing
rows = [mix((150, 210, 252), (178, 190, 246), i / 22) for i in range(23)]
lines = ['[INF]', 'Givre'] + [vb(c) for c in colors] + [vb(c) for c in rows]
with open(os.path.join(OUT, 'INFO.txt'), 'w', encoding='utf-8') as f:
    f.write('\n'.join(lines) + '\n')
print('skin written in', OUT)

# VIS.txt: where WinZik draws its visualizer (the spectrum of the sound), in the opened part of the player
with open(os.path.join(OUT, 'VIS.txt'), 'w') as f:
    f.write('127 107 124 15\n')
