"""
Autodoc functions
"""

import os
from datetime import datetime

import common as doc
from doc_state import *
from doc_state_machine import doc_state_machine


def __doc_app_state__(state, tab=" │  "):
    res = ""
    if "+Threads" in state:
        for i, tname in enumerate(state["+Threads"]):
            if tname[0] == "+":
                ch = "├─●" if i < len(state["+Threads"]) - 1 else "╰─●"
                res += f"{tab}  {ch} {tname[1:]}\n"
    return res


def __doc_application__(label, app):
    mdapp = f'\n## Real-time application: "{label[1:]}"\n\n'
    mdapp += f"Below are descrbed the states and threads of the real-time application {label[1:]}.\n"

    mdapp += "\n"
    mdapp += "```\n"
    # mdapp += f'╭{"─"*(len(label)-1)}╮\n'
    # mdapp += f"│{label[1:]}│\n"
    # mdapp += f'╰┬{"─"*(len(label)-2)}╯\n'
    states = app["+States"]

    for i, (state, obj) in enumerate(states.items()):
        if state[0] == "+":
            mdapp += f" - {state[1:]}\n"
            for thread in obj["+Threads"]:
                if thread[0] == "+":
                    mdapp += f"   - {thread[1:]}\n"
    #     ch = "├─▷" if i < len(states) - 1 else "╰─▷"
    #     tab = " │  " if i < len(states) - 1 else "    "
    #     if label[0] == "+":
    #         mdapp += f" {ch} {label[1:]}\n"
    #         mdapp += __doc_app_state__(obj, tab)
    mdapp += "```\n"
    for label, obj in states.items():
        if label[0] == "+":
            mdapp += f'\n### State: "{label[1:]}"\n'
            mdapp += doc_state(label, obj, app)
    return mdapp


def document(fname, args, config):
    """Document MARTe object."""
    doc.set_path(os.path.join(args.destination, fname))
    doc.set_config(args)
    if not os.path.isdir(doc.path()):
        os.mkdir(doc.path())
    now = datetime.now()  # current date and time
    today = now.strftime("%d/%m/%Y")
    mddoc = "---\n"
    mddoc += "toc: true\n"
    mddoc += f"title: {fname} Documentation\n"
    mddoc += "author: MARTe AutoDOC\n"
    mddoc += "titlepage: true\n"
    mddoc += f"date: {today}\n"
    mddoc += "geometry: margin=2cm\n"
    mddoc += "---\n\n"

    mddoc += f"# {fname}\n"
    for label, obj in config.items():
        if "Class" in obj:
            if obj["Class"] == "RealTimeApplication":
                mddoc += __doc_application__(label, obj)
            if obj["Class"] == "StateMachine":
                mddoc += f'\n## State-Machine: "{label[1:]}"\n'
                mddoc += doc_state_machine(label[1:], obj)
    fpath = os.path.join(doc.path(), f"{fname}.md")
    outpath = os.path.join(doc.path(), fname)
    logging.info(f"Saving markdown: {fpath}")
    with open(fpath, "w") as file:
        file.write(mddoc)
    if doc.build():
        logging.info(f"Generating html: {outpath}.html")
        os.system(
            f"pandoc --css pandoc/styling.css --resource-path={doc.path()} --embed-resource --to html5 -s {fpath} -o {outpath}.html"
        )
        logging.info(f"Generating pdf: {outpath}.pdf")
        os.system(
            f"pandoc -H pandoc/disable_float.tex --resource-path={doc.path()} -s {fpath} -o {outpath}.pdf"
        )
