from typing import List
from pathlib import Path

from edalize.utils import EdaCommands


class Make(object):
    def __init__(self, flow_options):
        self.build_options = flow_options.get("flow_make_options", [])

    def get_build_command(self):
        return ("make", self.build_options)

    def write(self, commands: EdaCommands, work_root: Path):
        outfile = work_root / Path("Makefile")
        with open(outfile, "w") as f:
            f.write("#Auto generated by Edalize\n\n")
            for v in commands.variables:
                f.write(v + "\n")
            if commands.variables:
                f.write("\n\n")
            if not commands.default_target:
                raise RuntimeError("Internal Edalize error. Missing default target")

            f.write(f"all: {commands.default_target}\n")

            for c in commands.commands:
                f.write(f"\n{' '.join(c.targets)}:")
                for d in c.depends:
                    f.write(" " + d)
                if c.order_only_deps:
                    f.write(" |")
                    for d in c.order_only_deps:
                        f.write(" " + d)

                f.write("\n")

                env_prefix = ""
                if c.variables:
                    env_prefix += "env "
                    for key, value in c.variables.items():
                        env_prefix += f"{key}={value} "

                for command in c.commands:
                    if command:
                        f.write(
                            f"\t$(EDALIZE_LAUNCHER) {env_prefix}{' '.join([str(x) for x in command])}\n"
                        )
