import os
from pathlib import Path
import glob
import pandas as pd
import matplotlib
# matplotlib.use('TkAgg')
# matplotlib.use('module://backend_interagg')
import matplotlib.pyplot as plt
import seaborn as sns

diris=['./results/ourdataset_balanced','./results/fabiano_normal','./results/ourdataset_normal',
      './results/feature_selection_normal','./results/fabiano_balanced','./results/fontana_balanced',
      './results/fontana_normal']

label = {'XGB': 'XGB', 'CatBoostClassifier': 'CBoost', 'LGB': 'LGBM', 'RandomForest': 'RF',
         'Bagging': 'Bagging', 'XGBRF': 'XGBRF', 'AdaBoost': 'AB', 'ExtraTree': 'ET', 'MLP': 'MLP',
         'GaussianProcess': 'GP', 'DT': 'DT', 'SVM': 'SVM', 'LogisticRegression': 'LR', 'LinearSVC': 'LSVM',
         'SGD': 'SGD', 'LDA': 'LDA', 'KNN': 'KNN', 'Perceptron': 'Perceptron', 'QDA': 'QDA', 'PassiveAggressive': 'PA',
         'Ridge': 'Ridge', 'NB': 'GNB', 'GradientBoosting': 'GB', 'MultinomialNB': 'MNB', 'NuSVC': 'Nu-SVM',
         'BernoulliNB': 'BNB', 'NearestCentroid': 'NC', 'ComplementNB': 'CNB'}

for dirc in diris:
    file_name = r'%s/FinalAccuracy.txt' % dirc
    myfile = Path(file_name)

    if myfile.exists():
        os.remove(file_name)
        with open(file_name, 'a+') as x_file1:
            x_file1.write('Algorithm&Accuracy&Kappa&F1&Recall&Precision&Roc measure&MatthewsCoff\n')
            x_file1.close()
    else:
        with open(file_name, 'a+') as x_file1:
            x_file1.write('Algorithm&Accuracy&Kappa&F1&Recall&Precision&Roc measure&MatthewsCoff\n')
            x_file1.close()

    for o in os.listdir(dirc):
        path = os.path.join(dirc, o)
        if os.path.isdir(path):
            if os.path.isdir(path):
                filepath = path + "/Accuracy.txt"
                if os.path.exists(filepath):
                    print(filepath)
                    df = pd.read_csv(filepath, sep="&")
                    df.columns = ['Algorithm', 'Accuracy', 'Kappa', 'F1', 'Recall', 'Precision', 'Roc_measure',
                                  'MatthewsCoff']
                    df['Algorithm'] = df['Algorithm'].str.replace('.\t', '')
                    df['MatthewsCoff'] = df['MatthewsCoff'].str.replace('\\', '')

                    with open(file_name, 'a+') as x_file:
                        x_file.write('%s.' % label[df['Algorithm'].iloc[0]])
                        x_file.write('& %.4f' % df['Accuracy'].mean())
                        x_file.write('& %.4f' % df['Kappa'].mean())
                        x_file.write('& %.4f' % df['F1'].mean())
                        x_file.write('& %.4f' % df['Recall'].mean())
                        x_file.write('& %.4f' % df['Precision'].mean())
                        x_file.write('& %.4f' % df['Roc_measure'].mean())
                        x_file.write('& %.4f \n' % df['MatthewsCoff'].astype(float).mean())
                        x_file.close()


#### Generate the plot

df1=pd.read_csv('./results/ourdataset_normal/FinalAccuracy.txt', sep="&").values
# df1.index +=1
df2=pd.read_csv('./results/feature_selection_normal/FinalAccuracy.txt', sep="&").values
data=pd.DataFrame([df1[:,0], df1[:,2],df2[:,2]]).transpose()
data=data.sort_values(by=[1],ascending=False).values
sns.set_context("paper")

# sns.set_style("darkgrid", {"axes.facecolor": ".9"})

# create a color palette
palette = plt.get_cmap('Set1')

# width1 = 26
# height1 = 16
# width_height_1 = (width1, height1)
#
# plt.figure(figsize=width_height_1)
plt.ion()


plt.plot( data[:,1], color='blue', linestyle='solid', marker='*', markerfacecolor='white', markersize=6, label='Imbalanced data')
plt.plot( data[:,2], color='red', linestyle='solid', marker='+', markerfacecolor='white', markersize=6, label='Balanced data')

plt.xlabel("Algorithms", fontsize=16)
plt.ylabel("Roc (%)", fontsize=16)
plt.yticks(fontsize=16)
# plt.ylim(0.51, 0.98)
plt.xticks(fontsize=16)
# plt.xticks([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27], data[:,0], rotation=65)

plt.xticks([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27], data[:,0], rotation=65)
plt.grid(True)
l = plt.legend(fontsize=16,loc="best")
l.set_zorder(25)
plt.show()
# plt.savefig('./plots/books_read.png')