"""產生工具列的圖示（SF Symbols 風格線條圖示）：上一頁、下一頁、重新載入、
首頁、書籤（空心 / 實心）、下載。另外從左側圖示列的資料夾產生分頁上用的
小圖示。

用法：python3 -I packaging/icon/make_toolbar_icons.py
（分頁小圖示要先跑過 make_sidebar_icons.py）
輸出：resources/icons/tb-<名稱>-<light|dark>[-disabled]@<1|2>x.png，編譯時由
src/shared/icons.rs 用 include_bytes! 打包進執行檔。

單位是 pt（1x = 1px、2x = 2px），先用 16 倍大畫再縮小，線條才平滑。
"""

import math
import os

from PIL import Image, ImageDraw

HERE = os.path.dirname(__file__)
OUT = os.path.join(HERE, "..", "..", "resources", "icons")

S = 18            # 圖示邊長（pt）
SS = 16           # 每 pt 幾個 px
STROKE = 1.6      # 線寬（pt）
COLORS = {
    "light": (72, 72, 77),
    "dark": (210, 210, 215),
    "light-disabled": (190, 190, 195),
    "dark-disabled": (90, 90, 95),
}
ACCENT = {"light": (0, 122, 255), "dark": (10, 132, 255)}


def canvas():
    return Image.new("L", (S * SS, S * SS), 0)


def pts(*xy):
    return [(xy[i] * SS, xy[i + 1] * SS) for i in range(0, len(xy), 2)]


def line(d, *xy):
    d.line(pts(*xy), fill=255, width=round(STROKE * SS), joint="curve")
    r = STROKE * SS / 2
    for x, y in pts(*xy)[:: max(1, len(xy) // 2 - 1)]:   # 線頭畫圓，端點才是圓的
        d.ellipse((x - r, y - r, x + r, y + r), fill=255)


def back():
    m = canvas(); d = ImageDraw.Draw(m)
    line(d, 3.5, 9, 14.5, 9)
    line(d, 8, 4.5, 3.5, 9, 8, 13.5)
    return m


def forward():
    return back().transpose(Image.FLIP_LEFT_RIGHT)


def reload():
    m = canvas(); d = ImageDraw.Draw(m)
    cx, cy, r = 9, 9.5, 5.6
    w = round(STROKE * SS)
    d.arc(((cx - r) * SS, (cy - r) * SS, (cx + r) * SS, (cy + r) * SS), start=-40, end=250, fill=255, width=w)
    # 箭頭：在弧的起點（右上）
    a = math.radians(-40)
    ex, ey = cx + r * math.cos(a), cy + r * math.sin(a)
    d.polygon(pts(ex + 2.6, ey - 3.4, ex + 0.9, ey + 1.6, ex - 3.4, ey - 1.6), fill=255)
    return m


def home():
    m = canvas(); d = ImageDraw.Draw(m)
    line(d, 2.5, 9, 9, 3, 15.5, 9)
    line(d, 4.5, 7.5, 4.5, 15, 13.5, 15, 13.5, 7.5)
    line(d, 7.6, 15, 7.6, 11, 10.4, 11, 10.4, 15)
    return m


def star_points():
    cx, cy, ro, ri = 9, 9.6, 7.2, 3.0
    out = []
    for i in range(10):
        r = ro if i % 2 == 0 else ri
        a = math.radians(-90 + i * 36)
        out += [cx + r * math.cos(a), cy + r * math.sin(a)]
    return out


def star():
    m = canvas(); d = ImageDraw.Draw(m)
    p = star_points()
    d.line(pts(*(p + p[:4])), fill=255, width=round(STROKE * SS), joint="curve")
    return m


def star_fill():
    m = canvas(); d = ImageDraw.Draw(m)
    p = star_points()
    d.polygon(pts(*p), fill=255)
    d.line(pts(*(p + p[:4])), fill=255, width=round(STROKE * SS), joint="curve")
    return m


def download():
    m = canvas(); d = ImageDraw.Draw(m)
    line(d, 9, 2.8, 9, 11)
    line(d, 5.5, 7.6, 9, 11.1, 12.5, 7.6)
    line(d, 3, 11.5, 3, 15, 15, 15, 15, 11.5)
    return m


def more():
    """「⋮」更多選單：三個垂直排列的圓點。"""
    m = canvas(); d = ImageDraw.Draw(m)
    r = 1.45
    for cy in (4.2, 9, 13.8):
        d.ellipse(((9 - r) * SS, (cy - r) * SS, (9 + r) * SS, (cy + r) * SS), fill=255)
    return m


def save(mask, name, theme, rgb):
    img = Image.new("RGBA", mask.size, rgb + (0,))
    img.putalpha(mask)
    for scale in (1, 2):
        path = os.path.join(OUT, f"tb-{name}-{theme}@{scale}x.png")
        img.resize((S * scale, S * scale), Image.LANCZOS).save(path)
        print(path)


def tab_icons():
    """分頁上的小圖示（16pt）：文件、影片頁，從左側圖示列的大圖裁出圖示部分。"""
    for name, theme in [(n, t) for n in ("docs", "media", "remote") for t in ("light", "dark")]:
        src = Image.open(os.path.join(OUT, f"sidebar-{name}-{theme}@2x.png"))
        icon = src.crop((0, 0, src.width, 72)).crop(src.crop((0, 0, src.width, 72)).getbbox())
        for scale in (1, 2):
            size = 16 * scale
            k = size / max(icon.size)
            small = icon.resize((round(icon.width * k), round(icon.height * k)), Image.LANCZOS)
            out = Image.new("RGBA", (size, size), (0, 0, 0, 0))
            out.alpha_composite(small, ((size - small.width) // 2, (size - small.height) // 2))
            path = os.path.join(OUT, f"tb-tab-{name}-{theme}@{scale}x.png")
            out.save(path)
            print(path)


def main():
    os.makedirs(OUT, exist_ok=True)
    for name, draw in [("back", back), ("forward", forward), ("reload", reload),
                       ("home", home), ("star", star), ("download", download), ("more", more)]:
        mask = draw()
        for theme, rgb in COLORS.items():
            save(mask, name, theme, rgb)
    fill = star_fill()
    for theme, rgb in ACCENT.items():
        save(fill, "star-fill", theme, rgb)
    tab_icons()


if __name__ == "__main__":
    main()
