#!/usr/bin/env python3
"""Generate the figures of the interface chapter, docs/interface/.

The figures are original schematic drawings. The play-screen and spell-book
layouts are drawn from the button rectangles that docs/interface/PLAY_SCREEN.md
and SPELL_BOOK.md give, read from the DOS START.EXE; the input chain, the camp
menus and the start menu transcribe README.md, CAMP_MENUS.md and
OTHER_SCREENS.md. The program reads no file and reproduces no game graphics.

Usage:
    python3 scripts/interface/make_interface_figures.py [output_directory]

The default is docs/interface/img/.
"""
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
sys.path[:0] = [str(Path(__file__).resolve().parent), str(ROOT / 'scripts/common')]
import flowcharts  # noqa: E402
from svgkit import (frame, write, box, arrow, text, INK, INK2, MUTED, GRID, BLUE, LIGHT, DARK,  # noqa: E402
                    ORANGE, SHADE, PALE, GREEN, SURF)

OUT = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / 'docs/interface/img'

# Button rectangles of the play screen (x, y, width, height), docs/interface/PLAY_SCREEN.md.
WALL = (24, 8, 128, 96)
THROW = [(0, 8, 88, 48), (88, 8, 88, 48)]
FLOOR_AHEAD = [(0, 72, 88, 29), (89, 72, 88, 29)]
FLOOR_PARTY = [(0, 102, 88, 18), (89, 102, 88, 18)]
ARROWS = [(3, 128), (24, 128), (45, 128), (3, 144), (24, 144), (45, 144)]
BOXES = [(x, y) for y in (2, 54, 106) for x in (184, 256)]
CAMP = (289, 177, 31, 21)
# Spell book, docs/interface/SPELL_BOOK.md.
TABS = [(68, 18), (86, 18), (104, 15), (122, 15), (140, 15), (158, 15)]
LINES = (75, 131, 97)
BOOK_ARROWS = (146, 168, 32, 10)
ABORT = (68, 168, 78, 10)


def input_chain():
    flowcharts.chain(
        OUT / 'interface-input.svg', 'From a key or a click to an action',
        'Every click and almost every key goes through the list of buttons on the screen.',
        'How the game handles input. A key press or a mouse press joins a queue; Alt+S and Alt+M act as they are '
        'queued. Each pass of the game loop reads one event and walks the active button list in order: a button '
        'whose key matches, or under a press of a mouse button it answers to, runs its action; an action that '
        'returns 0 lets the walk go on, any other value ends it. A key that no button takes reaches the keyboard '
        'commands, which act only in keyboard control.',
        [('step', 'A key press or a mouse press joins the queue\n(Alt+S and Alt+M act at once)'),
         ('step', 'Each pass of the game loop reads one event'),
         ('ask', 'Is it a key of the next button, or a\npress in its rectangle?', 'yes',
          'Its action runs; 0 lets the walk\ngo on, anything else ends it', 'no: next button'),
         ('step', 'A key no button took reaches the keyboard\ncommands (keyboard control only)')])


def play_screen():
    s, ox, oy = 2, 30, 66
    W, H = 700, oy + 200 * s + 30
    out = frame(W, H, 'The buttons of the play screen',
                'The 320 by 200 play screen and its invisible buttons. In the view at the top left, 176 by 120: the '
                'wall in front (24, 8, 128 by 96), the two throw areas of the upper half, the floor of the block ahead '
                'and the floor of the party’s block, left and right. Below the view, six movement arrows of 21 by 16. '
                'On the right, six character boxes of 63 by 50, each with a name strip, a face and a hand area. At the '
                'bottom right, the camp button, 31 by 21.',
                'Screen pixels drawn at twice their size; the game draws no outline for these buttons.')
    R = lambda x, y, w, h, fill, stroke, dash=None, op=1: out.append(
        f'<rect x="{ox + x * s}" y="{oy + y * s}" width="{w * s}" height="{h * s}" fill="{fill}" fill-opacity="{op}" '
        f'stroke="{stroke}" stroke-width="1.4"' + (f' stroke-dasharray="{dash}"' if dash else '') + '/>')
    R(0, 0, 320, 200, SURF, GRID)
    R(0, 0, 176, 120, SHADE, MUTED)
    for r in THROW:
        R(*r, ORANGE, ORANGE, '4 3', 0.10)
    for r in FLOOR_AHEAD + FLOOR_PARTY:
        R(*r, GREEN, GREEN, None, 0.18)
    R(*WALL, 'none', BLUE, '6 3')
    out.append(text(ox + 88 * s, oy + 30 * s, 'wall in front', 11, BLUE, True, 'middle'))
    out.append(text(ox + 44 * s, oy + 14 * s, 'throw left', 10, ORANGE, None, 'middle'))
    out.append(text(ox + 132 * s, oy + 14 * s, 'throw right', 10, ORANGE, None, 'middle'))
    out.append(text(ox + 88 * s, oy + 86 * s, 'floor, block ahead', 10, GREEN, True, 'middle'))
    out.append(text(ox + 88 * s, oy + 111 * s, "floor, party's block", 10, GREEN, True, 'middle'))
    labels = ['↶', '↑', '↷', '←', '↓', '→']
    for (x, y), l in zip(ARROWS, labels):
        R(x, y, 21, 16, PALE, BLUE)
        out.append(text(ox + (x + 10.5) * s, oy + (y + 8) * s, l, 13, DARK, True, 'middle'))
    out.append(text(ox + 80 * s, oy + 136 * s, 'movement arrows', 10.5, INK2, None, 'start'))
    for i, (x, y) in enumerate(BOXES):
        R(x, y, 63, 50, SURF, INK2)
        R(x, y, 63, 8, LIGHT, 'none')
        R(x, y + 8, 33, 33, PALE, BLUE)
        R(x + 32, y + 8, 31, 33, SHADE, MUTED)
        out.append(text(ox + (x + 31) * s, oy + (y + 4) * s, f'name {i + 1}', 9, DARK, None, 'middle'))
        out.append(text(ox + (x + 16) * s, oy + (y + 24) * s, 'face', 9.5, DARK, None, 'middle'))
        out.append(text(ox + (x + 47) * s, oy + (y + 24) * s, 'hands', 9.5, INK2, None, 'middle'))
    R(*CAMP, PALE, BLUE)
    out.append(text(ox + (CAMP[0] + 15) * s, oy + (CAMP[1] + 10) * s, 'camp', 10.5, DARK, True, 'middle'))
    write(OUT, 'interface-play-screen.svg', out)


def spell_book():
    s, x0, y0, ox, oy = 4, 60, 114, 30, 70
    W, H = 700, oy + 70 * s + 40
    out = frame(W, H, 'The buttons of the spell book',
                'The spell book over the bottom of the view. Six tabs at y 121, 10 pixels high, from x 68: two of 18 '
                'pixels, then four of 15 every 18. Below them six lines of 97 by 6 pixels from x 75, y 131. At y 168, '
                'ABORT SPELL at x 68, 78 by 10, and the page arrows at x 146, 32 by 10.',
                'Screen pixels at four times their size; the book is drawn below the view.')
    X = lambda x: ox + (x - x0) * s
    Y = lambda y: oy + (y - y0) * s
    out.append(f'<rect x="{X(64)}" y="{Y(117)}" width="{120 * s}" height="{64 * s}" rx="6" fill="{SHADE}" stroke="{GRID}"/>')
    for k, (x, w) in enumerate(TABS):
        out.append(f'<rect x="{X(x)}" y="{Y(121)}" width="{w * s}" height="{10 * s}" fill="{PALE}" stroke="{BLUE}"/>')
        out.append(text(X(x) + w * s / 2, Y(126), str(k + 1), 12, DARK, True, 'middle'))
    lx, ly, lw = LINES
    out.append(f'<rect x="{X(lx)}" y="{Y(ly)}" width="{lw * s}" height="{34 * s}" fill="{SURF}" stroke="{INK2}" stroke-dasharray="4 3"/>')
    out.append(text(X(lx) + lw * s / 2, Y(ly) + 17 * s, 'six lines of 97 × 6, from y 131', 11, INK2, None, 'middle'))
    for (x, y, w, h), label in [(ABORT, 'ABORT SPELL'), (BOOK_ARROWS, 'arrows')]:
        out.append(f'<rect x="{X(x)}" y="{Y(y)}" width="{w * s}" height="{h * s}" fill="{PALE}" stroke="{BLUE}"/>')
        out.append(text(X(x) + w * s / 2, Y(y) + h * s / 2, label, 11, DARK, True, 'middle'))
    out.append(text(X(64) + 120 * s + 16, Y(126), 'tabs 1 to 6, y 121', 11, INK2))
    out.append(text(X(64) + 120 * s + 16, Y(147), 'click a ready spell', 11, INK2))
    out.append(text(X(64) + 120 * s + 16, Y(173), 'y 168, 10 high', 11, INK2))
    write(OUT, 'interface-spell-book.svg', out)


def camp_menu():
    W, H = 700, 360
    camp = ['Rest Party · R', 'Memorize Spells · M', 'Pray for Spells · P', 'Scribe Scrolls · S',
            'Preferences', 'Game Options · G', 'Exit · E, Escape']
    options = ['Load Game · L', 'Save Game · S', 'Drop Character · D', 'Quit Game · Q', 'Exit · E']
    prefs = ['Sounds are ON / OFF · S', 'Bar Graphs are ON / OFF · B', 'Exit · E']
    out = frame(W, H, 'The camp menus',
                'The camp menu and the two menus it opens, with the key of each button. Camp: Rest Party (R), Memorize '
                'Spells (M), Pray for Spells (P), Scribe Scrolls (S), Preferences, Game Options (G), Exit (E, Escape). '
                'Game Options: Load Game (L), Save Game (S), Drop Character (D), Quit Game (Q), Exit (E). Preferences: '
                'Sounds, Bar Graphs, Exit. Escape acts as the camp’s Exit in all three menus.',
                'Each button with its key; the clock is stopped while the camp is open.')

    def column(x, y, title, items, highlight=()):
        out.append(text(x, y - 14, title, 12.5, INK, True))
        for i, it in enumerate(items):
            yy = y + i * 30
            hl = i in highlight
            out.append(f'<rect x="{x}" y="{yy}" width="190" height="24" rx="5" fill="{PALE if hl else SURF}" '
                       f'stroke="{BLUE if hl else GRID}"/>')
            out.append(text(x + 10, yy + 12, it, 11, INK))
        return [y + i * 30 + 12 for i in range(len(items))]
    ys = column(30, 84, 'Camp', camp, (4, 5))
    yo = column(330, 84, 'Game Options', options)
    yp = column(330, 274, 'Preferences', prefs[:2])
    arrow(out, f'M220,{ys[5]} C270,{ys[5]} 280,{yo[0]} 327,{yo[0]}')
    arrow(out, f'M220,{ys[4]} C280,{ys[4]} 280,{yp[0]} 327,{yp[0]}')
    out.append(text(540, 286, 'and Exit · E', 11, INK2))
    out.append(text(540, 96, 'load and save menus:', 11, INK2))
    out.append(text(540, 112, 'six slots and Cancel', 11, INK2))
    write(OUT, 'interface-camp-menu.svg', out)


def start_menu():
    W, H = 700, 270
    lines = [('LOAD GAME IN PROGRESS', 'the load menu; a loaded game starts'),
             ('START A NEW PARTY', 'the party screen; the game starts'),
             ('TRANSFER EOB I PARTY', 'the transfer; the game starts'),
             ('RUN INTRODUCTION', 'the introduction, then this menu again'),
             ('EXIT TO DOS', 'the program ends')]
    out = frame(W, H, 'The start menu',
                'The five lines of the start menu, shown once after the introduction: LOAD GAME IN PROGRESS opens the '
                'load menu and starts the loaded game; START A NEW PARTY opens the party screen; TRANSFER EOB I PARTY '
                'starts the transfer; RUN INTRODUCTION plays the introduction and comes back; EXIT TO DOS ends the '
                'program. Leaving the load menu or a failed load shows the menu again.',
                'Played once, before the game loop; a failed load or a cancelled step comes back to it.')
    for i, (line, then) in enumerate(lines):
        y = 74 + i * 36
        out.append(f'<rect x="30" y="{y}" width="230" height="28" rx="5" fill="{PALE}" stroke="{BLUE}"/>')
        out.append(text(42, y + 14, line, 11.5, INK, True))
        arrow(out, f'M260,{y + 14} L300,{y + 14}')
        out.append(text(310, y + 14, then, 11.5, INK2))
    write(OUT, 'interface-start-menu.svg', out)


if __name__ == '__main__':
    input_chain()
    play_screen()
    spell_book()
    camp_menu()
    start_menu()
