"""Software-only preview of an event list
lines are drawn in BED coordinates (where batter lands, nozzle offset re-applied)
actual gantry path is not shown here
"""
import numpy as np

from config import MachineConfig
from toolpath import Dwell, Event, ExtrudeOn, Move, SelectNozzle # import the events


def trace(events: list[Event], cfg: MachineConfig): # replay the events and return the strokes and travels
    """Replay events. Returns (strokes, travels): lists of (nozzle, (N,2) bed points)."""
    strokes, travels = [], []
    nozzle, pos, cur = None, None, None
    for e in events:
        if isinstance(e, SelectNozzle):
            nozzle, pos = e.nozzle, None
        elif isinstance(e, Move):
            bed = np.array(cfg.to_bed(nozzle, e.x, e.y))
            if e.printing:
                if cur is None:
                    cur = [pos]
                    strokes.append((nozzle, cur))
                cur.append(bed)
            else:
                cur = None
                if pos is not None:
                    travels.append((nozzle, [pos, bed]))
            pos = bed
        elif isinstance(e, ExtrudeOn):
            cur = None
    return [(n, np.array(s)) for n, s in strokes], [(n, np.array(t)) for n, t in travels]


def stats(events: list[Event], cfg: MachineConfig) -> dict:
    """accountant for the event list"""
    out = {"print_length": 0.0, "travel_length": 0.0, "time": 0.0, "strokes": 0, "nozzle_changes": 0,
           "print_length_by_nozzle": {}}
    last, nozzle = None, None
    for e in events:
        if isinstance(e, Move):
            if last is not None:
                d = float(np.hypot(e.x - last[0], e.y - last[1]))
                out["print_length" if e.printing else "travel_length"] += d
                if e.printing:
                    by = out["print_length_by_nozzle"]
                    by[nozzle] = by.get(nozzle, 0.0) + d
                out["time"] += d / e.speed
            last = (e.x, e.y)
        elif isinstance(e, Dwell):
            out["time"] += e.seconds
        elif isinstance(e, ExtrudeOn):
            out["strokes"] += 1
        elif isinstance(e, SelectNozzle):
            out["nozzle_changes"] += 1
            nozzle = e.nozzle
    return out


def render(events: list[Event], cfg: MachineConfig, out_path=None, show_travel=True, title=None):
    """draw the strokes and travels on the plot"""
    import matplotlib # import matplotlib only when needed
    if out_path is not None:
        matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle

    strokes, travels = trace(events, cfg) # trace the events and return the strokes and travels
    lim, area = cfg.travel_limits, cfg.print_area
    fig, ax = plt.subplots(figsize=(9, 9 * (lim.y_max - lim.y_min + 20) / (lim.x_max - lim.x_min + 20)))
    ax.add_patch(Rectangle((lim.x_min, lim.y_min), lim.x_max - lim.x_min, lim.y_max - lim.y_min,
                           fill=False, ls=":", ec="0.6", label="gantry travel limits"))
    ax.add_patch(Rectangle((area.x_min, area.y_min), area.x_max - area.x_min, area.y_max - area.y_min,
                           fc="#f4f1ea", ec="0.3", label="print area"))
    used = {e.nozzle for e in events if isinstance(e, SelectNozzle)}
    reach = cfg.reachable_area(used) if used else area
    if reach != area:   # nozzle offsets cut off part of the print area
        ax.add_patch(Rectangle((reach.x_min, reach.y_min), reach.x_max - reach.x_min, reach.y_max - reach.y_min,
                               fill=False, ls="--", ec="tab:green", label="reachable by all nozzles used"))
    ax.set_xlim(lim.x_min - 10, lim.x_max + 10)
    ax.set_ylim(lim.y_min - 10, lim.y_max + 10)
    ax.set_aspect("equal")

    # convert line width in mm to points so strokes are drawn at their real width
    fig.canvas.draw()
    bbox = ax.get_window_extent()
    pts_per_mm = bbox.width / (lim.x_max - lim.x_min + 20) * 72 / fig.dpi
    lw = max(cfg.print.line_width * pts_per_mm, 0.5)

    for n, s in strokes:
        ax.plot(s[:, 0], s[:, 1], color=cfg.nozzles[n].color, lw=lw, solid_capstyle="round",
                solid_joinstyle="round")
    if show_travel: # plot the travels
        for i, (n, t) in enumerate(travels):
            ax.plot(t[:, 0], t[:, 1], color="tab:blue", lw=0.7, ls="--", alpha=0.7,
                    label="travel" if i == 0 else None)
    for i, (n, s) in enumerate(strokes):   # print sequence numbers at stroke starts
        ax.annotate(str(i + 1), s[0], fontsize=6, color="tab:red", xytext=(2, 2), textcoords="offset points")
    st = stats(events, cfg)
    for n in cfg.print.color_order:
        if n in st["print_length_by_nozzle"]:
            ax.plot([], [], color=cfg.nozzles[n].color, lw=4,
                    label=f"nozzle {n} ({cfg.nozzles[n].name}): {st['print_length_by_nozzle'][n]:.0f} mm")

    ax.set_title(title or "Toolpath preview")
    ax.text(0.01, 0.01, f"print {st['print_length']:.0f} mm | travel {st['travel_length']:.0f} mm | "
            f"{st['strokes']} strokes | ~{st['time'] / 60:.1f} min",
            transform=ax.transAxes, fontsize=8, va="bottom")
    ax.set_xlabel("X (mm)")
    ax.set_ylabel("Y (mm)")
    ax.legend(loc="upper right", fontsize=7)
    if out_path is not None: # save the figure to the output path
        fig.savefig(out_path, dpi=150, bbox_inches="tight")
        plt.close(fig)
    return fig