import trimesh
import os
import json
import argparse

class FS:
    def readJSON(path: str):
        return json.loads((open(path)).read())

    def writeFile(data, filePath, fileName):

        file_to_open = filePath + fileName

        f = open(file_to_open, 'w')
        f.write(data)
        f.close()

    def readFile(path: str):
        return open(path).read()

    def readFilesTypeFolder(pathFolder: str, fileType='.json'):
        filesJson = list(
            filter(lambda x: x[-fileType.__len__():] == fileType,  os.listdir(pathFolder)))
        return list(map(lambda x: pathFolder + x, filesJson))

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--aspPath', help='asp generation folder')
    args = parser.parse_args()
    
    if args.aspPath == None:
        parser.print_help()
    aspPath = args.aspPath
    pathMeshes = 'sdf/meshes/'
    permissibleDepth = 0.5

    trimeshObjects = []
    meshes = FS.readFilesTypeFolder(aspPath + pathMeshes, '.obj')
    for el in meshes:
        trimeshObjects.append(trimesh.load(el))

    manager = trimesh.collision.CollisionManager()

    for el in range(len(trimeshObjects)):
        manager.add_object(str(meshes[el]), trimeshObjects[el])

    def set_to_dict(s):
        keys = list(s)
        values = [None] * len(s)
        return {k: v for k, v in zip(keys, values)}
    collisions = manager.in_collision_internal(True, True)

    recalculations = {}
    for el in collisions[collisions.__len__() - 1]:
        if (el.depth > permissibleDepth):
            labels = ''
            for key in set_to_dict(el.names).keys():     
                label = key[key.rfind('/') + 1:key.__len__() - 4]
                labels+=label + " "
            message = {
                'names': labels,
                'depth': el.depth,
                'point': el.point.tolist()
            }
            if(recalculations.get(labels) != None):
                recalculations[labels].append(message)
            else:
                recalculations[labels] = [message]

    if(len(list(recalculations.keys())) >= 1):
        messageError = {
            'status':False,
            'recalculations':recalculations
        }
        FS.writeFile(json.dumps(messageError, ensure_ascii=False, indent=4), aspPath,'intersection_geometry.json')
    else: 
        message = {
            'status':True,
            'recalculations': None
        }
        FS.writeFile(json.dumps(messageError, ensure_ascii=False, indent=4), aspPath,'intersection_geometry.json')



main()
 