import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
from HelperFunctions import *
from ClassifyMin import *

import matplotlib.ticker as tickers
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
import pandas as pd



def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]


def find_nearestIdx(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return idx



# TODO
# - Fallunterscheidung (Speedup) falls gesuchter value mu_gamma = q3
# - Also Add option to plot Minimization Output


# ----- Setup Paths -----
# InputFile  = "/inputs/cellsolver.parset"
# OutputFile = "/outputs/output.txt"

InputFile  = "/inputs/computeMuGamma.parset"
OutputFile = "/outputs/outputMuGamma.txt"

# path = os.getcwd()
# InputFilePath = os.getcwd()+InputFile
# OutputFilePath = os.getcwd()+OutputFile
# --------- Run  from src folder:
path_parent = os.path.dirname(os.getcwd())
os.chdir(path_parent)
path = os.getcwd()
print(path)
InputFilePath = os.getcwd()+InputFile
OutputFilePath = os.getcwd()+OutputFile
print("InputFilepath: ", InputFilePath)
print("OutputFilepath: ", OutputFilePath)
print("Path: ", path)

#---------------------------------------------------------------

print('---- Input parameters: -----')

mu1 = 1.0
# mu1 = 10.0
# lambda1 = 10.0
rho1 = 1.0
alpha = 2.0

# beta = 5.0
beta = 2.0 #TEST

theta = 1.0/4.0

lambda1 = 0.0
# gamma = 1.0/4.0

gamma = 'infinity'  #Elliptic Setting
# gamma = '0'       #Hyperbolic Setting
# gamma = 0.5


print('mu1: ', mu1)
print('rho1: ', rho1)
print('alpha: ', alpha)
print('beta: ', beta)
print('theta: ', theta)
print('gamma:', gamma)
print('----------------------------')


# --- define Interval of x-va1ues:
xmin = 0.0
xmax = 1.0


numPoints = 1000
Theta_Values = np.linspace(xmin, xmax, num=numPoints)
print('Theta_Values:', Theta_Values)


B1_Values = []
B2_Values = []

b1 = prestrain_b1(rho1, beta, alpha,theta)
b2 = prestrain_b2(rho1, beta, alpha,theta)

b1_Vec = np.vectorize(prestrain_b1)
b2_Vec = np.vectorize(prestrain_b2)

Theta_Values = np.array(Theta_Values)
B1_Values_alphaNeg1 = b1_Vec(rho1, beta, -1.0,Theta_Values)
B1_Values_alphaNeg10 = b1_Vec(rho1, beta, -10.0,Theta_Values)
B1_Values_alpha2= b1_Vec(rho1, beta, 2.0 ,Theta_Values)
B1_Values_alpha10= b1_Vec(rho1, beta, 10.0 ,Theta_Values)
# B2_Values = b2_Vec(rho1, beta, alpha,Theta_Values)
B2_Values_alphaNeg1 = b2_Vec(rho1, beta, -1.0,Theta_Values)
B2_Values_alphaNeg10 = b2_Vec(rho1, beta, -10.0,Theta_Values)
B2_Values_alpha2= b2_Vec(rho1, beta, 2.0 ,Theta_Values)
B2_Values_alpha10= b2_Vec(rho1, beta, 10.0 ,Theta_Values)


B1_Values_beta05 = b1_Vec(rho1, 0.5, alpha ,Theta_Values)
B1_Values_beta1  = b1_Vec(rho1, 1.0, alpha ,Theta_Values)
B1_Values_beta2  = b1_Vec(rho1, 2.0, alpha ,Theta_Values)
B1_Values_beta10 = b1_Vec(rho1, 10, alpha  ,Theta_Values)
# ---

B2_Values_beta01 = b2_Vec(rho1, 0.1, alpha ,Theta_Values)
B2_Values_beta05 = b2_Vec(rho1, 0.5, alpha ,Theta_Values)
B2_Values_beta1  = b2_Vec(rho1, 1.0, alpha ,Theta_Values)
B2_Values_beta2  = b2_Vec(rho1, 2.0, alpha ,Theta_Values)
B2_Values_beta10 = b2_Vec(rho1, 10, alpha  ,Theta_Values)


# print('B1_Values:', B1_Values)
# print('B2_Values:', B2_Values)



# --- Convert to numpy array
# B1_Values = np.array(B1_Values)
# B2_Values  = np.array(B2_Values)
B1_Values_alphaNeg1  = np.array(B1_Values_alphaNeg1)
B1_Values_alphaNeg10  = np.array(B1_Values_alphaNeg10)
B1_Values_alpha2  = np.array(B1_Values_alpha2)
B1_Values_alpha10  = np.array(B1_Values_alpha10)
B2_Values_alphaNeg1  = np.array(B2_Values_alphaNeg1)
B2_Values_alphaNeg10  = np.array(B2_Values_alphaNeg10)
B2_Values_alpha2  = np.array(B2_Values_alpha2)
B2_Values_alpha10  = np.array(B2_Values_alpha10)



B1_Values_beta05= np.array(B1_Values_beta05)
B1_Values_beta1  = np.array(B1_Values_beta1 )
B1_Values_beta2  = np.array(B1_Values_beta2 )
B1_Values_beta10  = np.array(B1_Values_beta10 )
B2_Values_beta01  = np.array(B2_Values_beta01)
B2_Values_beta05  = np.array(B2_Values_beta05)
B2_Values_beta1  = np.array(B2_Values_beta1)
B2_Values_beta2  = np.array(B2_Values_beta2 )
B2_Values_beta10  = np.array(B2_Values_beta10)
# ---------------- Create Plot -------------------

#--- change plot style:  SEABORN
# plt.style.use("seaborn-paper")


#--- Adjust gobal matplotlib variables
# mpl.rcParams['pdf.fonttype'] = 42
# mpl.rcParams['ps.fonttype'] = 42
# mpl.rcParams['text.usetex'] = True
# mpl.rcParams["font.family"] = "serif"
# mpl.rcParams["font.size"] = "9"
# mpl.rcParams['axes.grid'] = True

# plt.rc('font', family='serif', serif='Times')
# plt.rc('font', family='serif')
# # plt.rc('text', usetex=True)  #also works...
# plt.rc('xtick', labelsize=8)
# plt.rc('ytick', labelsize=8)
# plt.rc('axes', labelsize=8)

# Styling
plt.style.use("seaborn-darkgrid")
# plt.style.use("seaborn-whitegrid")
plt.style.use("seaborn")
# plt.style.use("seaborn-paper")
# plt.style.use('ggplot')
# plt.rcParams["font.family"] = "Avenir"
# plt.rcParams["font.size"] = 16

# plt.style.use("seaborn-darkgrid")
mpl.rcParams['text.usetex'] = True
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = "10"
# mpl.rcParams['xtick.labelsize'] = 16mpl.rcParams['xtick.major.size'] = 2.5
# mpl.rcParams['xtick.bottom'] = True
# mpl.rcParams['ticks'] = True
mpl.rcParams['xtick.bottom'] = True
mpl.rcParams['xtick.major.size'] = 3
mpl.rcParams['xtick.minor.size'] = 1.5
mpl.rcParams['xtick.major.width'] = 0.75
mpl.rcParams['ytick.left'] = True
mpl.rcParams['ytick.major.size'] = 3
mpl.rcParams['ytick.minor.size'] = 1.5
mpl.rcParams['ytick.major.width'] = 0.75

mpl.rcParams.update({'font.size': 10})
mpl.rcParams['axes.labelpad'] = 3




#---- Scale Figure apropriately to fit tex-File Width
# width = 452.9679

# width as measured in inkscape
width = 6.28 *0.5
# width = 6.28

height = width / 1.618
# height = width / 2.5
#setup canvas first
fig = plt.figure()      #main
# fig, ax = plt.subplots()
# fig, (ax, ax2) = plt.subplots(ncols=2)

# fig,ax = plt.subplots(nrows=1,ncols=2,figsize=(width,height)) # more than one plot
# fig,ax = plt.subplots(nrows=1,ncols=1,figsize=(width,height)) # more than one plot
# fig,ax = plt.subplots(nrows=1,ncols=1,figsize=(width,height)) # more than one plot
# --- set overall Title
# fig.suptitle('Example of a Single Legend Shared Across Multiple Subplots')

# fig.subplots_adjust(left=.15, bottom=.16, right=.99, top=.97)  #TEST


# TEST
# mpl.rcParams['figure.figsize'] = (width+0.1,height+0.1)
# fig = plt.figure(figsize=(width+0.1,height+0.1))


# mpl.rcParams['figure.figsize'] = (width,height)
# fig = plt.figure(figsize=(10,6)) # default is [6.4,4.8] 6.4 is the width, 4.8 is the height
# fig = plt.figure(figsize=(width,height)) # default is [6.4,4.8] 6.4 is the width, 4.8 is the height
# fig = plt.figure(figsize=set_size(width))
# fig = plt.subplots(1, 1, figsize=set_size(width))

# --- To create a figure half the width of your document:#
# fig = plt.figure(figsize=set_size(width, fraction=0.5))



#--- You must select the correct size of the plot in advance
# fig.set_size_inches(3.54,3.54)


# ---- TODO ?:
# ax[0] = plt.axes((0.15,0.18,0.8,0.8))


# ax.tick_params(axis='x',which='major', direction='out',pad=3)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# ax.xaxis.set_major_locator(MultipleLocator(0.1))
# ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# a=ax.yaxis.get_major_locator()
# b=ax.yaxis.get_major_formatter()
# c = ax.get_xticks()
# d = ax.get_xticklabels()
# print('xticks:',c)
# print('xticklabels:',d)


ax = plt.axes((0.15,0.18,0.8,0.8))
# ax = plt.axes((0.1,0.1,0.5,0.5))
ax.grid(True,which='major',axis='both',alpha=0.3)
# ax[0].grid(True,which='major',axis='both',alpha=0.3)
# ax[1].grid(True,which='major',axis='both',alpha=0.3)
# ax.plot(Theta_Values,B1_Values , 'royalblue')
# ax.plot(Theta_Values,B2_Values , 'royalblue')

# l1 = ax[0].plot(Theta_Values,B1_Values_beta05 , label=r"$\theta_\mu = 0.5$")
# l2 = ax[0].plot(Theta_Values,B1_Values_beta1 , label=r"$\theta_\mu = 1.0$")
# l3 = ax[0].plot(Theta_Values,B1_Values_beta2 , label=r"$\theta_\mu = 2.0$")
# l4 = ax[0].plot(Theta_Values,B1_Values_beta10 , label=r"$\theta_\mu = 10.0$")
# ax[0].set_xlabel(r"volume fraction $\theta$")
# ax[0].set_ylabel(r"prestrain $b_1$")

# Labels to use in the legend for each line
# line_labels = [r"$\theta_\rho = -1.0$", r"$\theta_\rho = -10.0$", r"$\theta_\rho = 2.0$", r"$\theta_\rho = 10.0$"]
# line_labels = [r"$\theta_\mu = 0.5$", r"$\theta_\mu = 1.0$", r"$\theta_\mu = 2.0$", r"$\theta_\mu = 10.0$"]

# ax[1].plot(Theta_Values,B2_Values_alphaNeg1 , label=r"$\theta_\rho = -1.0$")
# ax[1].plot(Theta_Values,B2_Values_alphaNeg10 , label=r"$\theta_\rho = -10.0$")
# ax[1].plot(Theta_Values,B2_Values_alpha2 , label=r"$\theta_\rho = 2.0$")
# ax[1].plot(Theta_Values,B2_Values_alpha10 , label=r"$\theta_\rho = 10.0$")


# ---------------
# ax[1].plot(Theta_Values,B2_Values_beta05 , label=r"$\theta_\mu = 0.5$")
# ax[1].plot(Theta_Values,B2_Values_beta1 ,  label=r"$\theta_\mu = 1.0$")
# ax[1].plot(Theta_Values,B2_Values_beta2 ,  label=r"$\theta_\mu = 2.0$")
# ax[1].plot(Theta_Values,B2_Values_beta10 , label=r"$\theta_\mu = 10.0$")
# ax[1].set_xlabel(r"volume fraction $\theta$")
# ax[1].set_ylabel(r"prestrain $b_2$")


l1 = ax.plot(Theta_Values,B2_Values_beta01 , label=r"$\theta_\mu = 0.1$")
l2 = ax.plot(Theta_Values,B2_Values_beta05 , label=r"$\theta_\mu = 0.5$")
l3 = ax.plot(Theta_Values,B2_Values_beta1 ,  label=r"$\theta_\mu = 1.0$")
l4 = ax.plot(Theta_Values,B2_Values_beta2 ,  label=r"$\theta_\mu = 2.0$")
l5 = ax.plot(Theta_Values,B2_Values_beta10 , label=r"$\theta_\mu = 10.0$")
ax.set_xlabel(r"$\theta$", fontsize=10)
# ax.set_ylabel(r"prestrain $b_2$")


ax.set_ylabel(r"$\widehat B_{\mathrm{eff},2}^{\gamma}$",rotation=0, fontsize=10, labelpad=8)
# ax.set_title(r"$\widehat B_{\mathrm{eff},2}^{\gamma}$", fontsize=10)



line_labels = [r"$\theta_\mu = 0.1$",r"$\theta_\mu = 0.5$", r"$\theta_\mu = 1.0$", r"$\theta_\mu = 2.0$", r"$\theta_\mu = 10.0$"]


# plt.tight_layout()


# plt.subplots_adjust(wspace=0.4, hspace=0)


# ax.plot(X_Values[X_Values>0.136], Y_Values[X_Values>0.136])
# ax.plot(X_Values[X_Values<0.135], Y_Values[X_Values<0.135])
# ax.scatter(X_Values, Y_Values)
# ax.plot(X_Values, Y_Values)

# plt.plot(x_plotValues, y_plotValues,'.')
# plt.scatter(X_Values, Y_Values, alpha=0.3)
# plt.scatter(X_Values, Y_Values)
# plt.plot(X_Values, Y_Values,'.')
# plt.plot([X_Values[0],X_Values[-1]], [Y_Values[0],Y_Values[-1]])
# plt.axis([0, 6, 0, 20])

# ax.set_xlabel(r"volume fraction $\theta$", size=11)
# ax.set_ylabel(r"angle $\angle$",  size=11)


# plt.ylabel('$\kappa$')

# ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))
# ax.yaxis.set_major_locator(ticker.MultipleLocator(base=0.1))





# -- SETUP LEGEND
# ax.legend(prop={'size': 11})
# ax[0].legend()
# ax[1].legend(
# loc='upper left',
# bbox_to_anchor=(1,1))

# Create the legend
# handles, labels = ax.get_legend_handles_labels()

# fig.legend([l1, l2, l3, l4],     # The line objects
#            labels=line_labels,   # The labels for each line
#            loc="upper right",   # Position of legend
#            borderaxespad=0.15,    # Small spacing around legend box
#            # title="Legend Title"  # Title for the legend
#            bbox_to_anchor=(0.95,0.98)
#            )

# fig.legend([l1, l2, l3, l4],     # The line objects
#            labels=line_labels,   # The labels for each line
#            loc="upper left",   # Position of legend
#            borderaxespad=0.1,
#            # title="Legend Title"  # Title for the legend
#            bbox_to_anchor=(0.8,0.7)
#            )

# lg = ax.legend(bbox_to_anchor=(1.0, 0.75), loc='upper left')
# ax.tight_layout()


legend = fig.legend([l1, l2, l3, l4],     # The line objects
           labels=line_labels,   # The labels for each line
           loc="center right",   # Position of legend
           bbox_to_anchor=[1.35, 0.55],
           borderaxespad=0.15,    # Small spacing around legend box
           frameon=True
           # title="Legend Title"  # Title for the legend
           )

frame = legend.get_frame()
# frame.set_color('white')
frame.set_edgecolor('gray')

# Adjust the scaling factor to fit your legend text completely outside the plot
# (smaller value results in more space being made for the legend)
plt.subplots_adjust(right=0.8)
plt.tight_layout()

# ------------------ SAVE FIGURE
# tikzplotlib.save("TesTout.tex")
# plt.close()
# mpl.rcParams.update(mpl.rcParamsDefault)

# plt.savefig("graph.pdf",
#             #This is simple recomendation for publication plots
#             dpi=1000,
#             # Plot will be occupy a maximum of available space
#             bbox_inches='tight',
#             )
# plt.savefig("graph.pdf")




fig.set_size_inches(width, height)
fig.savefig('Plot-Prestrain-Theta_AlphaFix.pdf',dpi=300,bbox_extra_artists=(legend,),
            bbox_inches='tight')

# fig.savefig('Plot-Prestrain-Theta_AlphaFix.pdf',dpi=300,bbox_extra_artists=(lg,),
            # bbox_inches='tight')




# tikz_save('someplot.tex', figureheight='5cm', figurewidth='9cm')

# tikz_save('fig.tikz',
#            figureheight = '\\figureheight',
#            figurewidth = '\\figurewidth')

# ----------------------------------------


plt.show()
# #---------------------------------------------------------------