"""
State machine documentation.
"""

import logging
import os

import common


def doc_state_machine(name, obj):
    """Document state machine."""
    graph = f"digraph {name}" + "{\n"
    graph += "rankdir = LR;\n"
    # graph += "layout = circo;\n"
    graph += 'fontname="monospace";\n'
    graph += 'node [shape=egg, style="filled", fontname="monospace"];\n'
    graph += 'edge [fontname="monospace"];\n'
    first = True
    for key in obj:
        if key[0] == "+":
            state = key[1:]
            ids = common.format_name(state)
            graph += f"  {ids} [label=<<B>{state}</B>>"
            if first:
                graph += ", fillcolor=lightblue"
                first = False
            graph += "];\n"

            for x, y in obj[key].items():
                if x[0] == "+":
                    for a, b in y.items():
                        if a == "NextState":
                            graph += (
                                f"  {ids} -> {common.format_name(b)}[label={x[1:]}];\n"
                            )
    graph += "\n}"
    gpath = os.path.join(common.path(), name)
    logging.info(f"Saving state machine graph: {gpath}.dot")
    with open(gpath + ".dot", "w") as f:
        f.write(graph)

    if common.build():
        logging.info(f"Converting state machine graph: {gpath}.svg")
        os.system(f"dot -Tsvg -o{gpath}.svg {gpath}.dot")

    return f"![{name}]({name}.svg)" + "{width=90%}\n"
