class EdaCommands(object):
    class Command(object):
        def __init__(
            self, commands, targets, depends, order_only_deps=[], variables={}
        ):
            self.commands = commands
            self.targets = targets
            self.depends = depends
            self.order_only_deps = order_only_deps[:]
            self.variables = variables

    def __init__(self):
        self.commands = []
        self.variables = []
        self.header = "#Auto generated by Edalize\n\n"

    def add(self, command, targets, depends, order_only_deps=[], variables={}):
        if command and type(command[0]) == list:
            commands = command
        else:
            commands = [command]
        self.commands.append(
            self.Command(commands, targets, depends, order_only_deps, variables)
        )

    def add_var(self, var):
        self.variables.append(var)

    # Allow for portability between the main platforms
    def find_env_var_command(self):
        from sys import platform

        if platform == "linux" or platform == "linux2" or platform == "darwin":
            return "export"
        elif platform == "win32":
            return "set"
        return ""

    # Simplify the creation of flow environmental variables in the Makefile
    def add_env_var(self, key, value):
        self.variables.append(f"{self.find_env_var_command()} {key}={value}")

    def set_default_target(self, target):
        self.default_target = target

    def write(self, outfile):
        with open(outfile, "w") as f:
            f.write(self.header)
            for v in self.variables:
                f.write(v + "\n")
            if self.variables:
                f.write("\n\n")
            if not self.default_target:
                raise RuntimeError("Internal Edalize error. Missing default target")

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

            for c in self.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"
                        )


# Helper function to strip potential version from the end of a file_type (for example, converting
# vhdlSource-2008 -> vhdlSource)
def get_file_type(file_obj):
    file_type = file_obj.file_type

    for i, c in enumerate(file_type):
        if c == "-":
            return file_type[0:i]

    return file_type
