import salome_pluginsmanager
import GmeshBuild
from ctypes import windll
import SalomeToCenos

GMSH= GmeshBuild.GmeshBuild()
#filename=dialog.file_save()


def meshToCenos(context):
    global SalomeToCenos, GMSH, cenDict, windll
    import json
    # Show error if mesh not selected
    msErrorText = GMSH.meshIsSelected()
    if msErrorText:
        msgBox = QMessageBox()
        msgBox.setWindowTitle("Mesh to CENOS")
        msgBox.setText("ERROR: " + msErrorText)
        msgBox.exec_()
        return
    with open(os.environ['TEMP'] + '\\cenos\\' + os.environ['SESSION_GUID']  + '.json') as json_file:
        jsondata = json_file.read()
        data = json.loads(jsondata)

    foldername = data['args']['caseDir']

    mesh = GMSH.findSelectedMesh()
    # check names
    badNames = GMSH.checkNames()
    if badNames:
        msgBox = QMessageBox()
        msgBox.setWindowTitle("Mesh to CENOS")
        errorMsg = "ERROR: These names cannot be used for group names in CENOS: \n"
        for badName in badNames:
            badName = badName.encode('charmap').decode('utf-8')
            print(badName, errorMsg)
            errorMsg = errorMsg +"    - " + badName + "\n"
        msgBox.setText(errorMsg)
        msgBox.exec_()
        return
		
    # Get lists of geometry and mesh groups
    meshDim = GMSH.getMeshDimensionality(mesh)
    areaList = GMSH.get2DGroups()

    if meshDim == 3:
        lineList = []
        volumeList = GMSH.get3DGroups()
    else:
        lineList = GMSH.get1DGroups()
        volumeList = []

    allGeomGroupList = []
    allGeomGroupList.extend(volumeList + areaList + lineList)

    # Check if mesh file exists.
    if GMSH.mayWriteMeshFile(foldername):
    
        # execute group selection dialogue
        msErrorText = 1
        while msErrorText:
            allMeshGroupList = GMSH.getMeshGroups()
            selectedGroupNames = []
            group_count = len(volumeList) + len(areaList) + len(lineList) + len(allMeshGroupList)
            if (group_count):
                Gdialog = SalomeToCenos.SalomeMeshToCenos(volumeList, areaList, lineList, allMeshGroupList)
                Gdialog.exec_()
                # get list of selected group names from group selection dialogue
                selectedGroupNames = Gdialog.getSelectedGroupNames()
                if not Gdialog.wasOk():
                    return
            # selected Geometry group list 
            selectedGeomGroupList = [x for x in allGeomGroupList if x.GetName() in selectedGroupNames]
			
            #check if overlapping groups are selected
            overlappingGroups = GMSH.checkOverlapping(selectedGroupNames)
            if overlappingGroups:
                msgBox = QMessageBox()
                msgBox.setWindowTitle("Mesh to CENOS")
                print(overlappingGroups)
                errorMsg = "ERROR: These groups have overlapping entities and therefore cannot be exported to CENOS at the same time: \n"
                for overlapMessage in overlappingGroups:
                    errorMsg = errorMsg +"    - " + overlapMessage + "\n"
                msgBox.setText(errorMsg)
                msgBox.exec_()
                return

            GMSH.updateGroups(selectedGeomGroupList)
    
            # Allow Cenos UI to set foreground.
            windll.user32.AllowSetForegroundWindow(-1)

            # Check Mesh quality
            if meshDim == 2:
                (warnElms_AR, errElms_AR) = GMSH.checkAspectRatios2D(GMSH.findSelectedMesh(), 1000, 10000)
                if len(errElms_AR)>0:
                    GMSH.createMeshGroup(errElms_AR, "Aspect ratio error elements", "FACE")
                    msgBox = QMessageBox()
                    msgBox.setWindowTitle("Mesh to CENOS")
                    msgBox.setText("ERROR: " + str(len(errElms_AR)) + " elements found with aspect ratio > 10000. Such mesh will result in computation errors. A group under 'Groups of Faces/Volumes' has been created with these elements. Please check your mesh!" )
                    msgBox.exec_()
            

            if meshDim == 3:
                (warnElms_AR, errElms_AR) = GMSH.checkAspectRatios3D(GMSH.findSelectedMesh(), 1000, 10000)
                if len(errElms_AR)>0:
                    GMSH.createMeshGroup(errElms_AR, "Aspect ratio error elements", "VOLUME")
                    msgBox = QMessageBox()
                    msgBox.setWindowTitle("Mesh to CENOS")
                    msgBox.setText("ERROR: " + str(len(errElms_AR)) + " elements found with aspect ratio > 10000. Such mesh will result in computation errors. A group under 'Groups of Faces/Volumes' has been created with these elements. Please check your mesh!" )
                    msgBox.exec_()

            (warnElms_Taper, errElms_Taper) = GMSH.checkTaperRatios(GMSH.findSelectedMesh(), 0.3, 0.5)
            if len(errElms_Taper)>0:
                GMSH.createMeshGroup(errElms_Taper, "Taper error elements", "FACE")
                msgBox = QMessageBox()
                msgBox.setWindowTitle("Mesh to CENOS")
                msgBox.setText("ERROR: " + str(len(errElms_Taper)) + " elements found with taper > 0.5. Such mesh will result in computation errors. A group under 'Groups of Faces/Volumes' has been created with these elements. Please check your mesh!" )
                msgBox.exec_()

            if len(errElms_Taper)==0 and len(errElms_AR)==0:
            # Write mesh.
                msErrorText = GMSH.WriteMesh(foldername)
                if msErrorText:
                    msgBox = QMessageBox()
                    msgBox.setWindowTitle("Mesh to CENOS")
                    msgBox.setText("ERROR: " + msErrorText)
                    msgBox.exec_()
            break
		
def geometryToCenos(context):
    global SalomeToCenos,  GMSH
    import json
    activeStudy = context.study
    #Gdialog.exec_()
    #if Gdialog.wasOk():
        #filename = Gdialog.getData()
    with open(os.environ['TEMP'] + '\\cenos\\' + os.environ['SESSION_GUID']  + '.json') as json_file:
        jsondata = json_file.read()
        data = json.loads(jsondata)

    foldername = data['args']['caseDir']

    # Check if geometry file exists.
    if GMSH.mayWriteGeometryFile(foldername):
        windll.user32.AllowSetForegroundWindow(-1)
        chNr = GMSH.WriteGeometry(foldername)
        msgBox = QMessageBox()
        msgBox.setWindowTitle("Geometry to CENOS")
        msgBox.setText("Geometry was saved successfully!")
        msgBox.exec_()
    else:
        msgBox = QErrorBox()
        msgBox.setWindowTitle("Geometry to CENOS")
        msgBox.setText("Geometry saving failed!")
        msgBox.exec_()

salome_pluginsmanager.AddFunction('Mesh To CENOS',
                                    'Creates Mesh for CENOS',
                                    meshToCenos)

salome_pluginsmanager.AddFunction('Geometry To CENOS',
                                    'Saves Geometry to CENOS',
                                    geometryToCenos)

