"""The small badges of the play list lines (the kind of file: MP3, WAV, MID, CD, and VID for the films), drawn pixel
by pixel in a 3x5 font: sharp at every zoom (the anti-aliased text of small sizes blurs). The colour of each badge is
taken from the skin's own (its most frequent colour), VID gets the MP3 one.
  python3 tools/skins/badges.py assets/skins/givre [--all]     --all: the 5 badges, else only the missing ones
"""
import os
import sys
from collections import Counter
from PIL import Image

FONT = {  # 3 x 5
    'M': ['101', '111', '111', '101', '101'], 'P': ['110', '101', '110', '100', '100'], '3': ['111', '001', '011', '001', '111'],
    'W': ['101', '101', '111', '111', '101'], 'A': ['010', '101', '111', '101', '101'], 'V': ['101', '101', '101', '101', '010'],
    'I': ['111', '010', '010', '010', '111'], 'D': ['110', '101', '101', '101', '110'], 'C': ['011', '100', '100', '100', '011'],
}
KINDS = {'infomp3': 'MP3', 'infowav': 'WAV', 'infomid': 'MID', 'infocd': 'CD', 'infovid': 'VID'}
DEFAULT = {'infomp3': (0, 200, 0), 'infowav': (0, 170, 220), 'infomid': (220, 170, 0), 'infocd': (200, 200, 200), 'infovid': (230, 90, 220)}


def colour(path, fallback):
    if not os.path.isfile(path):
        return fallback
    im = Image.open(path).convert('RGBA')
    seen = Counter(p[:3] for p in im.getdata() if p[3] > 200 and sum(p[:3]) > 90)
    return seen.most_common(1)[0][0] if seen else fallback


def badge(label, rgb):
    im = Image.new('RGBA', (17, 9), (0, 0, 0, 0))
    px = im.load()
    for x in range(1, 16):          # a rounded 1px frame
        px[x, 0] = px[x, 8] = rgb + (255,)
    for y in range(1, 8):
        px[0, y] = px[16, y] = rgb + (255,)
    width = len(label) * 4 - 1
    x0 = (17 - width) // 2
    for i, ch in enumerate(label):
        for y, row in enumerate(FONT[ch]):
            for x, bit in enumerate(row):
                if bit == '1':
                    px[x0 + i * 4 + x, 2 + y] = rgb + (255,)
    return im


def main(skin, every):
    files = {k: os.path.join(skin, k + '.png') for k in KINDS}
    mp3 = colour(files['infomp3'], DEFAULT['infomp3'])
    for key, label in KINDS.items():
        if not every and os.path.isfile(files[key]):
            continue
        rgb = colour(files[key], DEFAULT[key]) if key != 'infovid' else colour(files['infovid'], mp3)
        badge(label, rgb).save(files[key])
    print('badges of', skin)


if __name__ == '__main__':
    main(sys.argv[1], '--all' in sys.argv)
