#!/usr/bin/env python3

from stl import mesh

files = ["steamvrthread.stl"]
scadFiles = ["threads.scad"]

fileData = {}
scadFileData = {}

def getVertexId(vertices, vertex):
    i = 0
    for v in vertices:
        if v[0] == vertex[0] and v[1] == vertex[1] and v[2] == vertex[2]:
            return i
        i += 1
    return -1

# 3D meshes
for file in files:
    current = mesh.Mesh.from_file(file)
    vertices = []
    triangles = []
    vId = 0
    for triangle in current.points:
        t = [0, 0, 0]
        point = 0
        for i in [0, 3, 6]:
            v = (triangle[i], triangle[i + 1], triangle[i + 2])
            vertexId = getVertexId(vertices, v)
            if vertexId >= 0:
                t[point] = vertexId
            else:
                t[point] = vId
                vertices.append(v)
                vId += 1
            point += 1
        triangles.append(t)
    id = file[0:-4]
    fileData[id] = (vertices, triangles)

with open("resources.hpp", "w") as f:
    f.write("#pragma once\n");
    f.write("// AUTOGENERATED FILE - DO NOT EDIT\n");
    for key, data in fileData.items():
        vString = "{"
        tString = "{"
        vLength = 0
        tLength = 0
        first = True
        for vertex in data[0]:
            for v in vertex:
                if not first:
                    vString += ", "
                first = False
                vString += str(v)
                vLength += 1
        first = True
        for triangle in data[1]:
            for t in triangle:
                if not first:
                    tString += ", "
                first = False
                tString += str(t)
                tLength += 1
        vString += "}"
        tString += "}"
        f.write("const float " + key + "_VERTICES[" + str(vLength) + "] " + vString + ";\n");
        f.write("const unsigned int " + key + "_TRIANGLES[" + str(tLength) + "] " + tString + ";\n");

# OpenSCAD resources
with open("scad.hpp", "w") as out:
    out.write("#pragma once\n");
    out.write("// AUTOGENERATED FILE - DO NOT EDIT\n");
    for file in scadFiles:
        filename = file[0:-5]
        out.write("const char* " + filename + "_SCAD = ")
        with open(file, "r") as f:
            isMultiComment = False
            for line in f.readlines():
                if line.strip().startswith("/*"):
                    isMultiComment = True
                if not line.strip().startswith("//") and not isMultiComment and not len(line.strip()) == 0:
                    l = line.strip().replace('"', '\\"')
                    out.write("\"" + l + "\\n\"\n")
                if line.strip().endswith("*/"):
                    isMultiComment = False
    out.write(";");
