#!/usr/bin/env python3
import sys, types
from PIL import Image, ImageDraw

records = []
orig_text = ImageDraw.ImageDraw.text

def spy(self, xy, text, *a, **kw):
    records.append((list(xy), text, kw.get('font'), kw.get('anchor')))
    return orig_text(self, xy, text, *a, **kw)

ImageDraw.ImageDraw.text = spy

g = types.ModuleType("gen")
code = compile(open("studiosoft_hc27_carousel_gen.py").read(),
               "studiosoft_hc27_carousel_gen.py", "exec")
exec(code, g.__dict__)


def analyze(slide_fn, name):
    n0 = len(records)
    slide_fn()
    recs = records[n0:]
    boxes = []
    for xy, text, font, anchor in recs:
        drw = ImageDraw.Draw(Image.new("RGB", (8, 8)))
        b = drw.textbbox((0, 0), text, font=font)
        wd, ht = b[2] - b[0], b[3] - b[1]
        if anchor == "rt":
            x0, x1 = xy[0] - wd, xy[0]
        else:
            x0 = xy[0] + b[0]
        y0 = xy[1] + b[1]
        boxes.append((x0, y0, x0 + wd, y0 + ht, text[:42]))
    print("\n=== %s (%d items) ===" % (name, len(boxes)))
    overlap = False
    for i in range(len(boxes)):
        for j in range(i + 1, len(boxes)):
            a, bb = boxes[i], boxes[j]
            ix = min(a[2], bb[2]) - max(a[0], bb[0])
            iy = min(a[3], bb[3]) - max(a[1], bb[1])
            if ix > 3 and iy > 3:
                print("  OVERLAP: '%s' <-> '%s' ix=%.0f iy=%.0f" % (a[4], bb[4], ix, iy))
                overlap = True
    if not overlap:
        print("  no overlaps")
    for (x0, y0, x1, y1, t) in boxes:
        if y1 > 1340 or y0 < 5:
            print("  EDGE: '%s' y0=%.0f y1=%.0f" % (t, y0, y1))


for fn, name in [(g.slide_cover, "slide1_cover"),
                 (g.slide_kenapa, "slide2_kenapa"),
                 (g.slide_isi, "slide3_isi"),
                 (g.slide_langkah, "slide4_langkah"),
                 (g.slide_cta, "slide5_cta")]:
    analyze(fn, name)
