"""Ink gaps between two glyphs set side by side (design document,
section 4.5.2): the least horizontal distance between the ink of the
left glyph and the ink of the right one, measured on lines 2 units
apart."""

STEP = 2
CURVE_STEPS = 24        # straight pieces per cubic curve


def _edges(outline):
    edges = []
    for contour in outline:
        start = current = None
        for segment in contour:
            if segment[0] == "move":
                start = current = segment[1]
            elif segment[0] == "line":
                edges.append((current, segment[1]))
                current = segment[1]
            else:
                (x0, y0), (x1, y1), (x2, y2), (x3, y3) = \
                    (current,) + tuple(segment[1:])
                for i in range(1, CURVE_STEPS + 1):
                    t = i / CURVE_STEPS
                    u = 1 - t
                    point = (
                        u ** 3 * x0 + 3 * u * u * t * x1
                        + 3 * u * t * t * x2 + t ** 3 * x3,
                        u ** 3 * y0 + 3 * u * u * t * y1
                        + 3 * u * t * t * y2 + t ** 3 * y3)
                    edges.append((current, point))
                    current = point
        if current is not None and current != start:
            edges.append((current, start))
    return edges


def profile(outline):
    """Height (a multiple of STEP) -> (left, right) end of the ink."""
    edges = _edges(outline)
    ys = [y for edge in edges for _, y in edge]
    result = {}
    if not ys:
        return result
    for y in range(int(min(ys)) // STEP * STEP, int(max(ys)) + STEP, STEP):
        line = y + 0.5
        xs = [x0 + (line - y0) * (x1 - x0) / (y1 - y0)
              for (x0, y0), (x1, y1) in edges
              if y0 <= line < y1 or y1 <= line < y0]
        if xs:
            result[y] = (min(xs), max(xs))
    return result


class Gaps:
    """Ink gaps of glyphs given by (outline, advance); profiles are
    computed once per outline."""

    def __init__(self):
        self._profiles = {}

    def _profile(self, glyph):
        key = id(glyph.outline)
        if key not in self._profiles:
            self._profiles[key] = (glyph.outline, profile(glyph.outline))
        return self._profiles[key][1]

    def gap(self, left, right, kern=0):
        """None if the two glyphs share no line of ink."""
        a, b = self._profile(left), self._profile(right)
        x = left.advance + kern
        values = [b[y][0] + x - a[y][1] for y in a if y in b]
        return min(values) if values else None
