#!/usr/bin/env python3
import itertools
import os
import struct

from PIL import Image

def rgb2h(r, g, b):
  return (r >> 3) << 11 | (g >> 2) << 5 | (b >> 3)

def bytes_line(bs):
  return '  ' + ' '.join(map(lambda i: f'{i:#x},', bs)) + '\n'

imgs = ['bg.png', 'moon.png', 'star.png', 'sleep.png']
for fname in imgs:
  alpha = []
  with Image.open(os.path.join('assets/', fname)) as img:
    w = img.width
    h = img.height

    if img.has_transparency_data:
      has_alpha = True
      data = [rgb2h(r, g, b) for r, g, b, _ in img.getdata()]
      alpha = [a for _, _, _, a in img.getdata()]
    else:
      data = [rgb2h(r, g, b) for r, g, b in img.getdata()]

  basename = os.path.splitext(fname)[0]
  with open(os.path.join('main/img/', basename + '.c'), 'w') as f:
    f.write(
      '#include <inttypes.h>\n\n'
      '#include "lvgl.h"\n\n'
      'static const uint8_t _data[] = {\n')

    for group in itertools.batched(data, 10):
      bs = bytearray()
      for c in group:
        bs += struct.pack('<H', c)

      f.write(bytes_line(bs))
    for group in itertools.batched(alpha, 20):
      f.write(bytes_line(group))

    f.write('};\n\n')

    f.write(
      f'const lv_image_dsc_t ui_img_{basename} = {{\n'
       '  .header.magic = LV_IMAGE_HEADER_MAGIC,\n'
      f'  .header.cf = LV_COLOR_FORMAT_RGB565{"A8" if alpha else ""},\n'
      f'  .header.w = {w},\n'
      f'  .header.h = {h},\n'
       '  .data_size = sizeof(_data),\n'
       '  .data = _data,\n'
       '};\n')