import string
from primitives_visitor import PrimitivesVisitor

class BootstrapVisitor(PrimitivesVisitor):
    def __init__(self, args):
        PrimitivesVisitor.__init__(self, args)

    def dump(self):
        call = self.value("call")
        access = self.value("access")
        resolve = self.value("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)

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

                source = "auto_%s" % source if isinstance(source, int) else source
                target = "auto_%s" % target if isinstance(target, int) else target
                # output.append("D %s,%s,%s\n" % (source, value, target))
                linkname = "%s_%s_%s" % (source, abs(hash(value)), target)
                output.append("Edge _%s_0(%s, %s)\n" % (linkname, source, target))
                output.append("Node _%s_2(%s)\n" % (linkname, value))
                output.append("Edge _%s_1(_%s_0, _%s_2)\n" % (linkname, linkname, linkname))
            elif t == "E":
                name, source, target = data
                source = source if self.first != source else "auto_initial_IP"
                target = target if self.first != target else "auto_initial_IP"
                name = "auto_%s" % name if isinstance(name, int) else name
                source = "auto_%s" % source if isinstance(source, int) else source
                target = "auto_%s" % target if isinstance(target, int) else target
                output.append("Edge _%s(_%s, _%s)\n" % (name, source, target))
        return ''.join(output)
