import FreeCAD
import os
import ImportGui
import shutil

from freecad.robossembler.usecases.export_assembly_them_all_usecase import ExportAssemblyThemAllUseCase
from freecad.robossembler.usecases.export_usecase import EXPORT_TYPES
from freecad.robossembler.usecases.export_usecase import ExportUseCase
from freecad.robossembler.usecases.get_sdf_geometry_usecase import SdfGeometryUseCase
from freecad.robossembler.usecases.assembly_parse_usecase import AssemblyParseUseCase
from freecad.robossembler.usecases.geometry_usecase import GeometryUseCase
from model.geometry_part import GeometryPart
from model.files_generator import FolderGenerator
from freecad.robossembler.helper.fs import FS
from PySide import QtGui



class RobossemblerFreeCadExportScenario:

    def call(self):
        print(2012)
        path = self.qtGuiFeature()
        if path == None:
            return
        self.systemHelper(path)

    def qtGuiFeature(self):
        if FreeCAD.ActiveDocument == None:
            FreeCAD.Console.PrintError("No active document")

        p = QtGui.QFileDialog.getExistingDirectoryUrl()
        path = p.path()

        if path == '':
            return None
        return path

    def systemHelper(self, path: str):

        root_label = FreeCAD.ActiveDocument.RootObjects[0].Label
        directory = path + '/' + root_label
        
        if not os.path.exists(directory):
            os.makedirs(directory)

        __objs__ = FreeCAD.ActiveDocument.RootObjects
        directoryExport = directory + '/'
        os.makedirs(directoryExport + FolderGenerator.ASSETS.value)
        os.makedirs(directoryExport + FolderGenerator.SDF.value)
        os.makedirs(directoryExport + FolderGenerator.SDF.value + '/' + FolderGenerator.MESHES.value)
        os.makedirs(directoryExport + FolderGenerator.ASSEMBlY.value)
        f = open(directory + "/step-structure.json", "w")
        f.write(AssemblyParseUseCase().toJson())
        f.close()
        self.geometry(directory)
        ExportAssemblyThemAllUseCase().call(directoryExport)         
        ImportGui.export(__objs__, directoryExport + 'assembly.step')
       
        shutil.make_archive(directory, 'zip', directory)

        shutil.rmtree(directory)
        return True

    def geometry(self, outPutsPath: str):
        exportUseCase = ExportUseCase.call(outPutsPath,EXPORT_TYPES.OBJ)
        for el in SdfGeometryUseCase().call(exportUseCase):
            FS.writeFile(el.toJSON(),   outPutsPath +
                         '/' + FolderGenerator.ASSETS.value + '/', el.name + '.json',)
             
     

 

 