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 subprocess import Popen, PIPE
#import sys

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

###################### Plotq12.py #########################
#  Input: Lame-Parameter Lambda
#  compute q12 entry of Q_hom for each Lambda
#  create plot:  q12(lambda)
###########################################################


InputFile  = "/inputs/cellsolver.parset"
OutputFile = "/outputs/output.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)

#---------------------------------------------------------------
Lambda_Values = np.linspace(0.0, 10.0, num=11)
# Lambda_Values = np.linspace(0.0, 5.0, num=6)
# Lambda_Values = np.linspace(3.0, 5.0, num=20)
print(Lambda_Values)
q12 = []

# Lambda_Values = [0.,          1.11111111,  2.22222222,  3.33333333,  4.44444444,  5.55555556,
#   6.66666667,  7.77777778,  8.88888889]
# q12 = [0.0, 0.063676,0.094143, 0.299630, 0.34867, 0.491484, 0.586567, 0.671976, 0.757724 ]


# --- Options
RUN = True
# RUN = False
# make_Plot = False
# make_Plot = True      # vll besser : Plot_muGamma
counter = 0

#material_prestrain_imp= "analytical_Example"
material_prestrain_imp= "parametrized_Laminate"

if RUN:
    for lambda1 in Lambda_Values:
        print("Run Cell-Problem for Lambda = ", lambda1)

        # LOGFILE = "./harmonicmaps_intoR"+ str(targetDim) + "_" + str(order) + "_" + str(numLevels) + ".log"
        LOGFILE = path + "/outputs/out_lambda" + str(counter) + ".log"
        print("LOGFILE: ", LOGFILE)
        counter += 1
        # print('gamma='+str(gamma))

        # with open(InputFilePath, 'r') as file:
        #     filedata = file.read()
        # filedata = re.sub('(?m)^lambda1=.*','lambda1='+str(lambda1),filedata)
        # f = open(InputFilePath,'w')
        # f.write(filedata)
        # f.close()

        executable = './build-cmake/src/Cell-Problem'

        # Run Cell-Problem
        # p = subprocess.Popen(executable + " cellsolver.parset"
        #                                             + " -lambda1 " + str(lambda1)
        #                                             + " | tee " + LOGFILE, shell=True)
        p = subprocess.Popen(executable + " " +path + "/inputs/cellsolver.parset"
                                                    + " -lambda1 " + str(lambda1)
                                                    + " -material_prestrain_imp " + str(material_prestrain_imp)
                                                    + " | tee " + LOGFILE, shell=True)
        p.wait() # wait

        # subprocess.run(['./build-cmake/src/Cell-Problem', './inputs/cellsolver.parset'],
        #                                      capture_output=True, text=True)




        with open(LOGFILE, 'r') as file:
            output  = file.read()

        ###Extract q12 from Output-File
        # with open(OutputFilePath, 'r') as file:
        #     output = file.read()
        tmp = re.search(r'(?m)^q_onetwo=.*',output).group()
        s = re.findall(r"[-+]?\d*\.\d+|\d+", tmp)
        q12Value = float(s[0])
        print("q12:", q12Value)
        q12.append(q12Value)
    # ------------end of for-loop -----------------
    print("(Output) Values of q12: ", q12)
# ----------------end of if-statement -------------


# Make Plot
# if make_Plot:

# --- Convert to numpy array
Lambda_Values = np.array(Lambda_Values)
q12= np.array(q12)

# ---------------- Create Plot -------------------
mpl.rcParams['text.usetex'] = True
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = "9"
width = 6.28 *0.5
height = width / 1.618
fig = plt.figure()
# ax = plt.axes((0.15,0.21 ,0.75,0.75))
ax = plt.axes((0.15,0.21 ,0.8,0.75))
ax.tick_params(axis='x',which='major', direction='out',pad=5)
ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
ax.xaxis.set_major_locator(MultipleLocator(2))
ax.xaxis.set_minor_locator(MultipleLocator(1))
ax.yaxis.set_major_locator(MultipleLocator(0.1))
# ax.yaxis.set_minor_locator(MultipleLocator(2))
ax.grid(True,which='major',axis='both',alpha=0.3)


ax.plot(Lambda_Values, q12, 'royalblue',   # data
marker='o',     # each marker will be rendered as a circle
markersize=4,   # marker size
markerfacecolor='orange',   # marker facecolor
markeredgecolor='black',  # marker edgecolor
markeredgewidth=1,       # marker edge width
# linestyle='--',            # line style will be dash line
linewidth=1)          # line width
ax.set_xlabel(r"$\lambda$")
ax.set_ylabel(r"$q_{12}$")

fig.set_size_inches(width, height)
fig.savefig('Plot-q12.pdf')

# plt.figure()
# plt.title(r'$q_{12}(\lambda)$-Plot')  # USE MATHEMATICAL EXPRESSIONS IN TITLE
# plt.plot(Lambda_Values, q12)
# plt.scatter(Lambda_Values, q12)
# # plt.axis([0, 6, 0, 20])
# plt.xlabel("$\lambda$")
# plt.ylabel("$q_{12}$")
# plt.legend()
plt.show()

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