import os
import FreeCADGui as Gui
import FreeCAD as App
from gui.init_gui import StabilityWorkbench
import json


def importObjAtPath(path: str):
    import importOBJ
    importOBJ.insert(u"" + path, App.ActiveDocument.Label)

    pass


def getFullPathObj(assemblyFolder: str, name: str):
    return assemblyFolder + 'sdf/meshes/' + name + '.obj'


def main():
    App.newDocument()
    env = json.loads((open('./env.json')).read())
    assemblyFolder = env.get('assemblyFolder')
    assemblyStructure = json.loads(
        (open(assemblyFolder + 'step-structure.json')).read())
    assemblyNumber = int(env.get('buildNumber')) - 1
    activeDetail = assemblyStructure[assemblyNumber]

    subassemblyNotParticipatingInMarkup = assemblyStructure[0:assemblyNumber - 1]
    detailOfTheMarkingZoneOfWhich = assemblyStructure[assemblyNumber - 1]
    importObjAtPath(getFullPathObj(assemblyFolder, activeDetail))
    importObjAtPath(getFullPathObj(
        assemblyFolder, detailOfTheMarkingZoneOfWhich))
    meshMark = App.ActiveDocument.Objects[0]
    meshDetailOfTheMarkZone = App.ActiveDocument.Objects[1]
    meshMark.ViewObject.ShapeColor = (0.31, 0.77, 0.87)
    meshDetailOfTheMarkZone.ViewObject.ShapeColor = (0.68, 0.66, 0.95)
    for el in list(map(lambda el: getFullPathObj(assemblyFolder, el), subassemblyNotParticipatingInMarkup)):
        importObjAtPath(el)
    for el in App.ActiveDocument.Objects[2:App.ActiveDocument.Objects.__len__()]:
        el.ViewObject.ShapeColor = (0.32, 0.05, 0.38)
    Gui.SendMsgToActiveView("ViewSelection")

    Gui.addWorkbench(StabilityWorkbench(env.get('resultURL')))
    Gui.activateWorkbench("StabilityWorkbench")


main()
