#!/usr/bin/env python3


import os
import re
import sys


PATTERN = re.compile(r"type (\w+) struct {")


def process_file(w, filepath):
    with open(filepath, "r") as r:
        content = "\n".join(r.readlines())
        for match in re.finditer(PATTERN, content):
            typename = match.group(1)
            w.write("\n")
            w.write("func New{}(\n".format(typename))
            start = match.end() + 1
            end = start + content[start:].index("}") - 1
            members = []
            for rawline in content[start:end].split("\n"):
                line = rawline.strip()
                if line == "" or line.startswith("//"):
                    continue
                tokens = line.split()
                members.append((tokens[0], tokens[1]))
            max_key_length = max(map(lambda mem: len(mem[0]), members))
            for (key, ty) in members:
                w.write("\t{} {},\n".format(key, ty))
            w.write(") {} {{\n".format(typename))
            w.write("\treturn {}{{\n".format(typename))
            for (key, _) in members:
                w.write("\t\t{}:{} {},\n".format(key, " " * (max_key_length - len(key)), key))
            w.write("\t}\n")
            w.write("}\n")


def main(path):
    with open(os.path.join(path, "constructors.go"), "w") as w:
        w.write("// Code generated by protoconstructorgen.py. DO NOT EDIT.\n")
        w.write("package {}\n".format(os.path.basename(path)))
        w.write("\n")
        w.write('import github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types"\n')
        w.write('import "time"\n')

        for filename in os.listdir(path):
            if filename.endswith(".pb.go"):
                process_file(w, os.path.join(path, filename))


if __name__ == "__main__":
    main(sys.argv[1])
