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
import time
# from ClassifyMin import *
from ClassifyMin_New import *
# from scipy.io import loadmat #not Needed anymore?
import codecs
import sys


def ReadEffectiveQuantities(QFilePath = os.path.dirname(os.getcwd()) + '/outputs/QMatrix.txt', BFilePath = os.path.dirname(os.getcwd())+ '/outputs/BMatrix.txt'):
    # Read Output Matrices (effective quantities)
    # From Cell-Problem output Files : ../outputs/Qmatrix.txt , ../outputs/Bmatrix.txt
    # -- Read Matrix Qhom
    X = []
    # with codecs.open(path + '/outputs/QMatrix.txt', encoding='utf-8-sig') as f:
    with codecs.open(QFilePath, encoding='utf-8-sig') as f:
        for line in f:
            s = line.split()
            X.append([float(s[i]) for i in range(len(s))])
    Q = np.array([[X[0][2], X[1][2], X[2][2]],
                  [X[3][2], X[4][2], X[5][2]],
                  [X[6][2], X[7][2], X[8][2]] ])

    # -- Read Beff (as Vector)
    X = []
    # with codecs.open(path + '/outputs/BMatrix.txt', encoding='utf-8-sig') as f:
    with codecs.open(BFilePath, encoding='utf-8-sig') as f:
        for line in f:
            s = line.split()
            X.append([float(s[i]) for i in range(len(s))])
    B = np.array([X[0][2], X[1][2], X[2][2]])
    return Q, B



def SetParametersCellProblem(alpha,beta,theta,gamma,mu1,rho1,lambda1, InputFilePath = os.path.dirname(os.getcwd()) +"/inputs/computeMuGamma.parset"):
    with open(InputFilePath, 'r') as file:
        filedata = file.read()
    filedata = re.sub('(?m)^alpha=.*','alpha='+str(alpha),filedata)
    filedata = re.sub('(?m)^beta=.*','beta='+str(beta),filedata)
    filedata = re.sub('(?m)^theta=.*','theta='+str(theta),filedata)
    filedata = re.sub('(?m)^gamma=.*','gamma='+str(gamma),filedata)
    filedata = re.sub('(?m)^mu1=.*','mu1='+str(mu1),filedata)
    filedata = re.sub('(?m)^rho1=.*','rho1='+str(rho1),filedata)
    filedata = re.sub('(?m)^lambda1=.*','lambda1='+str(lambda1),filedata)
    f = open(InputFilePath,'w')
    f.write(filedata)
    f.close()

#TODO combine these...

def SetParametersComputeMuGamma(beta,theta,gamma,mu1,rho1, InputFilePath = os.path.dirname(os.getcwd()) +"/inputs/computeMuGamma.parset"):
    with open(InputFilePath, 'r') as file:
        filedata = file.read()
    filedata = re.sub('(?m)^beta=.*','beta='+str(beta),filedata)
    filedata = re.sub('(?m)^theta=.*','theta='+str(theta),filedata)
    filedata = re.sub('(?m)^gamma=.*','gamma='+str(gamma),filedata)
    filedata = re.sub('(?m)^mu1=.*','mu1='+str(mu1),filedata)
    filedata = re.sub('(?m)^rho1=.*','rho1='+str(rho1),filedata)
    f = open(InputFilePath,'w')
    f.write(filedata)
    f.close()




def RunCellProblem(alpha,beta,theta,gamma,mu1,rho1,lambda1, InputFilePath = os.path.dirname(os.getcwd()) +"/inputs/computeMuGamma.parset"):
        # with open(InputFilePath, 'r') as file:
        #     filedata = file.read()
        # filedata = re.sub('(?m)^gamma=.*','gamma='+str(gamma),filedata)
        # filedata = re.sub('(?m)^alpha=.*','alpha='+str(alpha),filedata)
        # filedata = re.sub('(?m)^beta=.*','beta='+str(beta),filedata)
        # filedata = re.sub('(?m)^theta=.*','theta='+str(theta),filedata)
        # filedata = re.sub('(?m)^mu1=.*','mu1='+str(mu1),filedata)
        # filedata = re.sub('(?m)^rho1=.*','rho1='+str(rho1),filedata)
        # f = open(InputFilePath,'w')
        # f.write(filedata)
        # f.close()
        SetParametersCellProblem(alpha,beta,theta,gamma,mu1,rho1,lambda1, InputFilePath)
        # --- Run Cell-Problem
        # Optional: Check Time
        # t = time.time()
        subprocess.run(['./build-cmake/src/Cell-Problem', './inputs/cellsolver.parset'],
                                             capture_output=True, text=True)
        # print('elapsed time:', time.time() - t)
        # --------------------------------------------------------------------------------------









def GetCellOutput(alpha,beta,theta,gamma,mu1,rho1,lambda1, InputFilePath = os.path.dirname(os.getcwd()) +"/inputs/computeMuGamma.parset",
                OutputFilePath = os.path.dirname(os.getcwd()) + "/outputs/outputMuGamma.txt" ):
        RunCellProblem(alpha,beta,theta,gamma,mu1,rho1,lambda1, InputFilePath)
        print('Read effective quantities...')
        Q, B = ReadEffectiveQuantities()
        # print('Q:', Q)
        # print('B:', B)
        return Q, B


# unabhängig von alpha...
def GetMuGamma(beta,theta,gamma,mu1,rho1, InputFilePath = os.path.dirname(os.getcwd()) +"/inputs/computeMuGamma.parset",
                OutputFilePath = os.path.dirname(os.getcwd()) + "/outputs/outputMuGamma.txt" ):
    # ------------------------------------ get mu_gamma ------------------------------
    # ---Scenario 1.1: extreme regimes
    if gamma == '0':
        # print('extreme regime: gamma = 0')
        mu_gamma = (1.0/6.0)*arithmeticMean(mu1, beta, theta) # = q2
        # print("mu_gamma:", mu_gamma)
    elif gamma == 'infinity':
        # print('extreme regime: gamma = infinity')
        mu_gamma = (1.0/6.0)*harmonicMean(mu1, beta, theta)   # = q1
        # print("mu_gamma:", mu_gamma)
    else:
        # --- Scenario 1.2:  compute mu_gamma with 'Compute_MuGamma' (much faster than running full Cell-Problem)
        # print("Run computeMuGamma for Gamma = ", gamma)

        SetParametersComputeMuGamma(beta,theta,gamma,mu1,rho1, InputFilePath)
        # with open(InputFilePath, 'r') as file:
        #     filedata = file.read()
        # filedata = re.sub('(?m)^gamma=.*','gamma='+str(gamma),filedata)
        # # filedata = re.sub('(?m)^alpha=.*','alpha='+str(alpha),filedata)
        # filedata = re.sub('(?m)^beta=.*','beta='+str(beta),filedata)
        # filedata = re.sub('(?m)^theta=.*','theta='+str(theta),filedata)
        # filedata = re.sub('(?m)^mu1=.*','mu1='+str(mu1),filedata)
        # filedata = re.sub('(?m)^rho1=.*','rho1='+str(rho1),filedata)
        # f = open(InputFilePath,'w')
        # f.write(filedata)
        # f.close()
        # --- Run Cell-Problem

        # Check Time
        # t = time.time()
        # subprocess.run(['./build-cmake/src/Cell-Problem', './inputs/cellsolver.parset'],
        #                                      capture_output=True, text=True)
        # --- Run Cell-Problem_muGama   -> faster
        # subprocess.run(['./build-cmake/src/Cell-Problem_muGamma', './inputs/cellsolver.parset'],
        #                                              capture_output=True, text=True)
        # --- Run Compute_muGamma (2D Problem much much faster)

        subprocess.run(['./build-cmake/src/Compute_MuGamma', './inputs/computeMuGamma.parset'],
                                                             capture_output=True, text=True)
        # print('elapsed time:', time.time() - t)

        #Extract mu_gamma from Output-File                                           TODO: GENERALIZED THIS FOR QUANTITIES OF INTEREST
        with open(OutputFilePath, 'r') as file:
            output = file.read()
        tmp = re.search(r'(?m)^mu_gamma=.*',output).group()                           # Not necessary for Intention of Program t output Minimizer etc.....
        s = re.findall(r"[-+]?\d*\.\d+|\d+", tmp)
        mu_gamma = float(s[0])
        # print("mu_gamma:", mu_gammaValue)
    # --------------------------------------------------------------------------------------
    return mu_gamma






def Compare_Classification(alpha,beta,theta,gamma,mu1,rho1,lambda1, InputFilePath = os.path.dirname(os.getcwd()) +"/inputs/computeMuGamma.parset"):
        # ---------------------------------------------------------------
        # Comparison of the analytical Classification 'ClassifyMin'
        # and the symbolic Minimizatio + Classification 'symMinimization'
        # ----------------------------------------------------------------
        comparison_successful = True
        eps = 1e-8

        # 1. Substitute Input-Parameters for the Cell-Problem
        with open(InputFilePath, 'r') as file:
            filedata = file.read()
        filedata = re.sub('(?m)^gamma=.*','gamma='+str(gamma),filedata)
        filedata = re.sub('(?m)^alpha=.*','alpha='+str(alpha),filedata)
        filedata = re.sub('(?m)^beta=.*','beta='+str(beta),filedata)
        filedata = re.sub('(?m)^theta=.*','theta='+str(theta),filedata)
        filedata = re.sub('(?m)^mu1=.*','mu1='+str(mu1),filedata)
        filedata = re.sub('(?m)^rho1=.*','rho1='+str(rho1),filedata)
        filedata = re.sub('(?m)^lambda1=.*','lambda1='+str(lambda1),filedata)
        f = open(InputFilePath,'w')
        f.write(filedata)
        f.close()
        # 2. --- Run Cell-Problem
        print('Run Cell-Problem ...')
        # Optional: Check Time
        # t = time.time()
        subprocess.run(['./build-cmake/src/Cell-Problem', './inputs/cellsolver.parset'],
                                             capture_output=True, text=True)


        # 3. --- Run Matlab symbolic minimization program: 'symMinimization'
        eng = matlab.engine.start_matlab()
        # s = eng.genpath(path + '/Matlab-Programs')
        s = eng.genpath(os.path.dirname(os.getcwd()))
        eng.addpath(s, nargout=0)
        # print('current Matlab folder:', eng.pwd(nargout=1))
        eng.cd('Matlab-Programs', nargout=0)  #switch to Matlab-Programs folder
        # print('current Matlab folder:', eng.pwd(nargout=1))
        Inp = False
        print('Run symbolic Minimization...')
        G, angle, type, kappa = eng.symMinimization(Inp,Inp,Inp,Inp, nargout=4)  #Name of program:symMinimization
        # G, angle, type, kappa = eng.symMinimization(Inp,Inp,Inp,Inp,path + "/outputs", nargout=4)  #Optional: add Path
        G = np.asarray(G) #cast Matlab Outout to numpy array
        # --- print Output ---
        print('Minimizer G:')
        print(G)
        print('angle:', angle)
        print('type:', type )
        print('curvature:', kappa)

        # 4. --- Read the effective quantities (output values of the Cell-Problem)
        # Read Output Matrices (effective quantities)
        print('Read effective quantities...')
        Q, B = ReadEffectiveQuantities()
        print('Q:', Q)
        print('B:', B)
        q1 = Q[0][0]
        q2 = Q[1][1]
        q3 = Q[2][2]
        q12 = Q[0][1]
        b1 = B[0]
        b2 = B[1]
        b3 = B[2]
        print("q1:", q1)
        print("q2:", q2)
        print("q3:", q3)
        print("q12:", q12)
        print("b1:", b1)
        print("b2:", b2)
        print("b3:", b3)

        # --- Check Assumptions:
        # Assumption of Classification-Lemma1.6:  [b3 == 0] & [Q orthotropic]
        # Check if b3 is close to zero
        assert (b3 < eps), "ClassifyMin only defined for b3 == 0 !"

        # Check if Q is orthotropic i.e. q13 = q31 = q23 = q32 == 0
        assert(Q[2][0] < eps and Q[0][2] < eps and Q[1][2] < eps and Q[2][1] < eps), "Q is not orthotropic !"

        # 5. --- Get output from the analytical Classification 'ClassifyMin'
        G_ana, angle_ana, type_ana, kappa_ana = classifyMin(q1, q2, q3, q12, b1, b2)
        print('Minimizer G_ana:')
        print(G_ana)
        print('angle_ana:', angle_ana)
        print('type_ana:', type_ana )
        print('curvature_ana:', kappa_ana)

        # 6. Compare
        # print('DifferenceMatrix:', G_ana - G )
        # print('MinimizerError (FrobeniusNorm):', np.linalg.norm(G_ana - G , 'fro') )

        if np.linalg.norm(G_ana - G , 'fro') > eps :
            comparison_successful = False
            print('Difference between Minimizers is too large !')
        if type != type_ana :
            comparison_successful = False
            print('Difference in type !')
        if abs(angle-angle_ana) > eps :
            comparison_successful = False
            print('Difference in angle is too large!')
        if abs(kappa-kappa_ana) > eps :
            comparison_successful = False
            print('Difference in curvature is too large!')


        if comparison_successful:
            print('Comparison successful')
        else:
            print('Comparison unsuccessful')

        return comparison_successful




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