"""Crops and arranges the shots of WinZik for its site (site/images) and the directory (assets/thumbnail.png)."""
import sys
from pathlib import Path
from PIL import Image

app = Path(sys.argv[1])
src = app / 'var/screenshots/site-src'
tests = app / 'var/screenshots/tests'
img = app / 'site/images'
img.mkdir(parents=True, exist_ok=True)
TEAL = (0, 128, 128)


def scale_of(im):
    """The zoom of the desktop in a shot (Desktop::layout): whole halves, the player and its list fit."""
    return max(1.0, min(4.0, int(min(im.width / 275, im.height / 510) * 2) / 2))


def windows(im, extra=0):
    """The player and its play list (desktop pixels 0..282 x 0..485)."""
    s = scale_of(im)
    return im.crop((0, 0, int(282 * s), int((485 + extra) * s)))


def lyrics(im, width=282):
    s = scale_of(im)
    return im.crop((0, im.height - int(25 * s), int(width * s), im.height))


def fit(im, w):
    return im.resize((w, round(im.height * w / im.width)), Image.LANCZOS)


player = Image.open(src / 'player.png').convert('RGB')
theskin = Image.open(src / 'theskin.png').convert('RGB')
fit(windows(player), 520).save(img / 'player.png')
fit(windows(theskin, 29), 520).save(img / 'the-skin.png')
fit(lyrics(player, 520), 1040).save(img / 'lyrics.png')
splash = Image.open(src / 'splash.png').convert('RGB')
# the splash: kept for the record in var/screenshots/site-src

for name, test in [('menu', 'menu'), ('compact', 'compact'), ('lock', 'lock'), ('about', 'a-propos'), ('files', 'files')]:
    f = tests / f'{test}.png'
    if f.exists():
        im = Image.open(f).convert('RGB')
        if name == 'compact':
            s = scale_of(im)
            im = im.crop((im.width - int(150 * s), 0, im.width, int(60 * s)))
            fit(im, 520).save(img / f'{name}.png')
        else:
            fit(im, 640).save(img / f'{name}.png')

# og.png 1200 x 630 and the thumbnail 16:9: the desktop of 1999, the player, the logo
logo = Image.open(app / 'assets/images/winzik.png').convert('RGB')
def poster(w, h):
    p = Image.new('RGB', (w, h), TEAL)
    win = windows(player)
    win = win.resize((round(win.width * (h - 40) / win.height), h - 40), Image.LANCZOS)
    p.paste(win, (w - win.width - 30, 20))
    lw = w - win.width - 90
    lg = fit(logo, lw)
    p.paste(lg, (30, (h - lg.height) // 2 - 40))
    ly = fit(lyrics(player, 282), lw)
    p.paste(ly, (30, (h - lg.height) // 2 + lg.height - 10))
    return p
poster(1200, 630).save(img / 'og.png')
poster(1280, 720).resize((640, 360), Image.LANCZOS).save(app / 'assets/thumbnail.png')
Image.open(app / 'assets/icon.png').convert('RGBA').resize((64, 64), Image.NEAREST).save(img / 'favicon.png')
print('site pictures in', img)
Image.open(app / 'assets/images/winzik.png').convert('RGB').save(img / 'logo.png')
