# -*- coding: utf-8 -*-
"""图 5-9　正向计算法（教材第 96 页）

按照片逐节点照录（节点三行：上排 ES/D/EF，中排活动名，下排留空）：
A 0/5/5、B 0/4/4、C 5/3/8、D 4/5/9、E 8/8/16、F 8/7/15、G 9/5/14、H 16/6/22。
连线：A→C、B→D、C→E、C→F、D→G、E→H、F→H、G→H。
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, save  # noqa: E402
from matplotlib.patches import Rectangle  # noqa: E402

OUT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                   'assets', '图5-9-正向计算法.png')

W, H = 16.0, 13.0
R1 = 4.4          # 上排高
R2 = 4.4          # 中排高


def node(ax, x, cy, name, top, bot=(None, None, None)):
    """三行三列活动节点：上排 ES/D/EF，中排活动名，下排 LS/TF/LF（可留空）。"""
    yt = cy + H / 2
    ax.add_patch(Rectangle((x, cy - H / 2), W, H, facecolor='white',
                           edgecolor='#1a365d', lw=1.5, zorder=3))
    y1, y2 = yt - R1, yt - R1 - R2
    for y in (y1, y2):
        ax.plot([x, x + W], [y, y], color='#1a365d', lw=1.2, zorder=4)
    for xv in (x + W / 3, x + 2 * W / 3):
        ax.plot([xv, xv], [y1, yt], color='#1a365d', lw=1.2, zorder=4)
        ax.plot([xv, xv], [cy - H / 2, y2], color='#1a365d', lw=1.2, zorder=4)
    for i, v in enumerate(top):
        if v is None:
            continue
        ax.text(x + W / 6 + i * W / 3, (yt + y1) / 2, str(v), ha='center', va='center',
                fontsize=12, color='#1a202c', zorder=5)
    ax.text(x + W / 2, (y1 + y2) / 2, name, ha='center', va='center',
            fontsize=13, color='#1a202c', zorder=5)
    for i, v in enumerate(bot):
        if v is None:
            continue
        ax.text(x + W / 6 + i * W / 3, (y2 + cy - H / 2) / 2, str(v), ha='center', va='center',
                fontsize=12, color='#1a202c', zorder=5)
    return dict(x=x, cy=cy, l=(x, cy), r=(x + W, cy),
                t=(x + W / 2, cy + H / 2), b=(x + W / 2, cy - H / 2))


def arr(ax, p1, p2):
    ax.annotate('', xy=p2, xytext=p1, zorder=2,
                arrowprops=dict(arrowstyle='-|>', color='#2b6cb0', lw=1.5,
                                shrinkA=0, shrinkB=0, mutation_scale=16))


def main():
    setup()
    fig, ax = canvas(11.0, 9.9, xlim=(0, 100), ylim=(6, 96))
    ax.set_aspect('equal')

    node(ax, 3, 66, 'A', (0, 5, 5))
    node(ax, 3, 30, 'B', (0, 4, 4))
    node(ax, 27, 66, 'C', (5, 3, 8))
    node(ax, 27, 30, 'D', (4, 5, 9))
    node(ax, 53, 86, 'E', (8, 8, 16))
    node(ax, 53, 52, 'F', (8, 7, 15))
    node(ax, 53, 16, 'G', (9, 5, 14))
    node(ax, 80, 52, 'H', (16, 6, 22))

    arr(ax, (19, 66), (27, 66))                 # A→C
    arr(ax, (19, 30), (27, 30))                 # B→D
    arr(ax, (43, 66), (53, 82))                 # C→E
    arr(ax, (43, 66), (53, 56))                 # C→F
    arr(ax, (43, 30), (53, 20))                 # D→G
    arr(ax, (69, 84), (80, 56))                 # E→H
    arr(ax, (69, 52), (80, 52))                 # F→H
    arr(ax, (69, 18), (80, 48))                 # G→H

    save(fig, OUT)


if __name__ == '__main__':
    main()
