PDF_OUTPUT = True
import matplotlib as mpl
if PDF_OUTPUT:
    mpl.use('pdf')
else:
    mpl.use('Agg')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
from matplotlib import cm
import re
import os
import json
import numpy as np
import pandas as pd
import json
from vtk import vtkUnstructuredGridReader
from vtk.util import numpy_support as VN
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
from matplotlib import cm
from multiprocessing import Pool
plt.style.use("seaborn-paper")
plt.rc('font', family='serif', serif='Times')
# plt.rc('text', usetex=True)
plt.rc('xtick', labelsize=8)
plt.rc('ytick', labelsize=8)
plt.rc('axes', labelsize=8)
width = 3.487
height = width / 1.618

# NO_OVERWRITE = False
NO_OVERWRITE = True


def get_data(filename):
    reader = vtkUnstructuredGridReader()
    reader.SetFileName(filename)
    reader.ReadAllVectorsOn()
    reader.ReadAllScalarsOn()
    reader.Update()

    data = reader.GetOutput()

    vtk_points = data.GetPoints()
    xyz3d = vtk_to_numpy( vtk_points.GetData() )
    xy = xyz3d[:,0:2]
    scalar_names = [reader.GetScalarsNameInFile(i) for i in range(0, reader.GetNumberOfScalarsInFile())]
    scalar_data = data.GetPointData()
    #scalar_names = scalar_data.GetArrayNames()
    def GetScalar(scalar_name):
        return vtk_to_numpy(scalar_data.GetArray(scalar_names.index(scalar_name)))
    lx = GetScalar("size_x") * 2
    ly = GetScalar("size_y") * 2
    damage = GetScalar("sigma_xx")
    #damage = GetScalar("plastic_strain")
    return pd.DataFrame({"coord_x":xy[:,0], "coord_y":xy[:,1],"lx":lx,"ly":ly,"damage":damage})

def get_data_all(folder,frame_number):
    #regex = re.compile(r'sim_\d+_{}'.format(frame_number))
    #files = list(filter(regex.search,os.listdir(folder)))
    #subframes = [get_data(folder + "/" + f) for f in files]
    #df = pd.concat(subframes)
    return get_data(folder+"/"+"mpData_{}.vtk".format(frame_number))




import subprocess

plt.rc('font', family='serif', serif='Times')
# plt.rc('text', usetex=True)
plt.rc('xtick', labelsize=8)
plt.rc('ytick', labelsize=8)
plt.rc('axes', labelsize=8)
width = 3.487
height = width / 1.618

water_height = 236
#output-0.5-strong/  output-0.5-weak/
# output_dir = "/mnt/c/Temp/ham-chalk-rl/output-0.16666666666666666_F_T_R_T/"
output_dir = "./beam_vis_data/output/"
outframes_dir = "./outframes/"
print(output_dir)


ice_height = 200

plt.close("all")
files = os.listdir(output_dir)
finalcsv = re.compile("mpData_\d+.vtk")
files_csvs = list(filter(finalcsv.match,files))

framenumber_regex = re.compile("\d+")
files_csvs = list(map(lambda x: framenumber_regex.findall(x)[-1],files_csvs))
files_csvs.sort(key=int)
print("files: {}".format(files_csvs))

xlim = [0,7.5]
ylim = [2.5,10.5]

aspect = (xlim[1]-xlim[0])/(ylim[1]-ylim[0])


scale= 3.487/16
# scale= 3.487/4
fig = plt.figure(figsize=(16*scale,16*scale),dpi=200)

def get_plot(i):
    fname = files_csvs[i]
    df = get_data_all(output_dir,fname)
    print("Plot frame {}".format(i),flush=True)
    ax = fig.add_subplot(111,aspect="equal")
    patch_list=[]
    for a_x, a_y,lx,ly,damage in zip(df["coord_x"],
                                     df["coord_y"],
                                     df["lx"],
                                     df["ly"],
                                     df["damage"]):
        patch = Rectangle(
            xy=(a_x-lx/2, a_y-ly/2) ,width=lx, height=ly,
            fill=None)
        patch_list.append(patch)
    #p = PatchCollection(patch_list,fc="none",ec="black")
    p = PatchCollection(patch_list, cmap=cm.jet, alpha=1)
    p.set_array(df["damage"])
    p.set_clim([-1e6,1e6])
    ax.add_collection(p)
    fig.colorbar(p,location="bottom",label="$\sigma_{xx}$")
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    plt.tight_layout()
    plt.savefig(outframes_dir+"frame_{:05}.pdf".format(i),dpi=1000)
    plt.clf()
i = 1
# for f in range(len(files_csvs)):
#     get_plot(f)
get_plot(3)
