#
# This file generates the sidebar/toctree for all RobotPy projects and should
# be copied to each project when it is updated
#

import os


def write_if_changed(fname, contents):

    try:
        with open(fname, "r") as fp:
            old_contents = fp.read()
    except:
        old_contents = ""

    if old_contents != contents:
        with open(fname, "w") as fp:
            fp.write(contents)


def generate_sidebar(conf, conf_api):

    # determine 'latest' or 'stable'
    # if not conf.do_gen:
    do_gen = os.environ.get("SIDEBAR", None) == "1" or conf["on_rtd"]
    version = conf["rtd_version"]

    lines = ["", ".. DO NOT MODIFY! THIS PAGE IS AUTOGENERATED!", ""]

    def toctree(name):
        lines.extend(
            [".. toctree::", "    :caption: %s" % name, "    :maxdepth: 2", ""]
        )

    def endl():
        lines.append("")

    def write(desc, link):
        if conf_api == "robotpy":
            args = desc, link
        elif not do_gen:
            return
        else:
            args = (
                desc,
                "https://robotpy.readthedocs.io/en/%s/%s.html" % (version, link),
            )

        lines.append("    %s <%s>" % args)

    def write_api(project, desc):
        if project != conf_api:
            if do_gen:
                args = desc, project, version
                lines.append(
                    "    %s API <https://robotpy.readthedocs.io/projects/%s/en/%s/api.html>"
                    % args
                )
        else:
            lines.append("    %s API <api>" % desc)

    #
    # Specify the sidebar contents here
    #

    toctree("Robot Programming")
    write("Getting Started", "getting_started")
    write("Installation", "install/index")
    write("Programmer's Guide", "guide/index")
    write("Frameworks", "frameworks/index")
    write("Hardware & Sensors", "hw")
    write("Camera & Vision", "vision/index")
    endl()

    toctree("API Reference")
    write_api("wpilib", "WPILib")
    write_api("pynetworktables", "NetworkTables")
    write_api("cscore", "CSCore")
    write_api("utilities", "Utilities")
    write_api("pyfrc", "PyFRC")
    write_api("ctre", "CTRE Libraries")
    write_api("navx", "NavX Library")
    write_api("rev", "SPARK MAX Library")
    endl()

    toctree("Additional Info")
    write("Troubleshooting", "troubleshooting")
    write("Support", "support")
    write("FAQ", "faq")
    endl()

    toctree("RobotPy Developers")
    write("Developer Documentation", "dev/index")
    endl()

    write_if_changed("_sidebar.rst.inc", "\n".join(lines))
