#!python3
import gmsh
from perturbMesh import perturbMesh, readCustomData
from math import sin, pi, sqrt
import subprocess

baseinput="replace vith the path where the output of ExtendSolution.m is located"
baseoutput="replace vith the path where the plots should be placed"

meshsize = 1

if __name__ == "__main__":
    gmsh.initialize()
    name = "Mesh_0{}_{}.msh"
    nameOriginal = name.format(meshsize, "per3")
    namePerturb = name.format(meshsize, "perturbed")
    modelname = gmsh.model.getCurrent()

    dataItems=("Solution", "Exact", "Error")
    data = {item: readCustomData(item+"0" + str(meshsize)) for item in dataItems}

    gmsh.option.setNumber("General.NoPopup", 1)
    gmsh.option.setNumber("General.Verbosity", 2)

    # Hide irrelevant stuff
    gmsh.option.setNumber("General.Axes", 1)
    gmsh.option.setNumber("General.SmallAxes", 0)
    gmsh.option.setNumber("Geometry.Points", 0)
    gmsh.option.setNumber("Mesh.SurfaceEdges", 0)
    gmsh.option.setNumber("View.ShowElement", 0)

    gmsh.open(nameOriginal)
    perturbMesh()
    gmsh.fltk.initialize()

    for item in dataItems:
        for part in ("real", "imaginary"):
            viewTag = gmsh.view.add("Mesh size 0.{}, {}, {} part.".format(meshsize,item, part))
            gmsh.view.option.setNumber(viewTag, 'Light', 0)
            #gmsh.view.option.setNumber(viewTag, 'View.AutoPosition', 9)
            gmsh.view.option.setNumber(viewTag, 'ColormapNumber', 12)
            gmsh.view.option.setNumber(viewTag, 'Visible', 1)
            gmsh.view.addHomogeneousModelData(viewTag,0,modelname,"NodeData",data[item]["tags"],data[item][part])
            gmsh.graphics.draw()
            gmsh.write(baseoutput+"/{}_0{}_{}.png".format(item, meshsize, part))
            gmsh.view.option.setNumber(viewTag, 'Visible', 0)

        viewTag = gmsh.view.add("Mesh size 0.{}, {}, {}.".format(meshsize,item, 'absolute value'))
        gmsh.view.option.setNumber(viewTag, 'Light', 0)
        gmsh.view.option.setNumber(viewTag, 'ColormapNumber', 12)
        gmsh.view.option.setNumber(viewTag, 'Visible', 1)
        gmsh.view.addHomogeneousModelData(viewTag,0,modelname,"NodeData",data[item]["tags"],
                                          [sqrt(data[item]["real"][idx]**2+data[item]["imaginary"][idx]**2) for idx in range(len(data[item]["tags"]))])
        gmsh.graphics.draw()
        gmsh.write(baseoutput+"/{}_0{}_{}.png".format(item, meshsize, "abs"))
        gmsh.write(baseoutput+"/{}_0{}_{}_tex.pgf".format(item, meshsize, "abs"))
        gmsh.view.option.setNumber(viewTag, 'Visible', 0)

    gmsh.fltk.run()
    gmsh.finalize()
