# -*- coding: utf-8 -*-
"""图 5-10　反向计算法 1（教材第 97 页）

按照片逐节点照录：上排 ES/D/EF 同图 5-9；下排只填最迟开始时间（LS）与
最迟完成时间（LF），中间的总浮动时间（TF）格留空（图 5-11 才填）。
A 0…5、B 2…6、C 5…8、D 6…11、E 8…16、F 9…16、G 11…16、H 16…22。
"""
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-10-反向计算法1.png')

W, H = 16.0, 13.0
R1 = 4.4
R2 = 4.4


def node(ax, x, cy, name, top, ls, 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):
        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)
    yb = cy - H / 2
    ax.text(x + W / 6, (y2 + yb) / 2, str(ls), ha='center', va='center',
            fontsize=12, color='#1a202c', zorder=5)
    ax.text(x + 5 * W / 6, (y2 + yb) / 2, str(lf), ha='center', va='center',
            fontsize=12, color='#1a202c', zorder=5)


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), 0, 5)
    node(ax, 3, 30, 'B', (0, 4, 4), 2, 6)
    node(ax, 27, 66, 'C', (5, 3, 8), 5, 8)
    node(ax, 27, 30, 'D', (4, 5, 9), 6, 11)
    node(ax, 53, 86, 'E', (8, 8, 16), 8, 16)
    node(ax, 53, 52, 'F', (8, 7, 15), 9, 16)
    node(ax, 53, 16, 'G', (9, 5, 14), 11, 16)
    node(ax, 80, 52, 'H', (16, 6, 22), 16, 22)

    arr(ax, (19, 66), (27, 66))
    arr(ax, (19, 30), (27, 30))
    arr(ax, (43, 66), (53, 82))
    arr(ax, (43, 66), (53, 56))
    arr(ax, (43, 30), (53, 20))
    arr(ax, (69, 84), (80, 56))
    arr(ax, (69, 52), (80, 52))
    arr(ax, (69, 18), (80, 48))

    save(fig, OUT)


if __name__ == '__main__':
    main()
