import string
from hutn_compiler.primitives_visitor import PrimitivesVisitor, Action

class BootstrapVisitor(PrimitivesVisitor):
    def __init__(self, args):
        PrimitivesVisitor.__init__(self, args)
        self.main = "--main" in args

        for f in args:
            if "--prepend:" in f:
                self.prepend_name = f.split(":", 1)[1]
                break
        else:
            self.prepend_name = "auto"

    def rename(self, name):
        if name == "initial_IP":
            return "%s_%s" % (self.prepend_name, name)
        else:
            return "%s_%s" % (self.prepend_name, name) if isinstance(name, int) else name

    def dump(self):
        if self.main:
            call = self.value(Action("call"))
            access = self.value(Action("access"))
            resolve = self.value(Action("resolve"))
            main = self.value("__main")
            self.dict(resolve, "var", main)
            self.dict(access, "var", resolve)
            self.dict(call, "func", access)
            self.dict(self.last_instruction, "next", call)
            ret = self.value(Action("return"))
            self.dict(call, "next", ret)

        output = []
        for t, data in self.output:
            if t == "N":
                output.append("Node %s_%s()\n" % (self.prepend_name, data))
            elif t == "V":
                name, value = data
                name = name if self.first != name else "initial_IP"
                output.append("Node %s_%s(%s)\n" % (self.prepend_name, name, value))
            elif t == "D":
                source, value, target = data
                source = source if self.first != source else "initial_IP"
                target = target if self.first != target else "initial_IP"

                source = self.rename(source)
                target = self.rename(target)
                output.append("Dict (%s, %s, %s)\n" % (source, value, target))
            elif t == "E":
                name, source, target = data
                source = source if self.first != source else "initial_IP"
                target = target if self.first != target else "initial_IP"
                name = self.rename(name)
                source = self.rename(source)
                target = self.rename(target)
                output.append("Edge _%s(_%s, _%s)\n" % (name, source, target))
        return ''.join(output)
