#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 23:56:42 2022

@author: emilydu
"""

__version__ = '0.0.1'

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 20:09:18 2022

@author: emilydu
"""

from ml_eis import *
import PySimpleGUI as sg
import matplotlib.figure
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
matplotlib.use("TkAgg")

#Decide theme of windows
sg.theme('LightBlue2')

# ------------------------------- Figure drawing code -------------------------------

def draw_figure_w_toolbar(canvas, fig, canvas_toolbar):
    plt.close('all')
    if canvas.children:
        for child in canvas.winfo_children():
            child.destroy()
    if canvas_toolbar.children:
        for child in canvas_toolbar.winfo_children():
            child.destroy()
    figure_canvas_agg = FigureCanvasTkAgg(fig, master=canvas)
    figure_canvas_agg.draw()
    toolbar = Toolbar(figure_canvas_agg, canvas_toolbar)
    toolbar.update()
    figure_canvas_agg.get_tk_widget().pack(side='right', fill='both', expand=1.5)


# ------------------------------- Toolbar function -------------------------------

class Toolbar(NavigationToolbar2Tk):
    def __init__(self, *args, **kwargs):
        super(Toolbar, self).__init__(*args, **kwargs)




# ------------------------------- Window1 CODE-------------------------------

# imagefile = b' '
# , sg.Image(imagefile, k='-IMAGE-')

def make_win1():
    buttons = [
        [sg.Button('Visualization', font='Any 13 bold'), sg.Button('Machine Learning',font='Any 13 bold')],
        [sg.Button('Exit', font='Any 12')]
        ]
    
    layout = [
        [sg.Text('Welcome to Machine Learning based on EIS',size=(40, 1), justification='center', font='Any 20')],
              [sg.Text('Please select one to start:', font='Any 14')],
              [sg.Column(buttons)]
              ]
   
    window = sg.Window('Machine Learning based on EIS', layout, finalize=True, margins=(20, 20))
    # window.set_min_size(window.size)
    
    return window




# ------------------------------- Window2 code -------------------------------


def make_win2():


    top_col = [
        [sg.T('*Needs more instruction', font='Any 14')], #title name
                [sg.T('Please select your input file:', font='Any 12'),sg.Input(key='-visual_file-'), sg.FileBrowse()], #file browse
                [sg.T('Cycle Number', font='Any 12'),sg.InputText(key='-number-')], #cycle number
                [sg.T('Please select the plotting sytle:', font='Any 12')], 
                [sg.Button('EIS', font='Any 13 bold'), sg.B('dqdv', font='Any 13 bold'), sg.B('Cycling', font='Any 13 bold')]
                           
                ]



    layout = [ 
        [sg.T('Data Visualization', size=(50, 1), justification='center', font='Any 20 bold')],
               [sg.Column(top_col, element_justification='left')], 
               [sg.T('Controls panel:', font='Any 14 bold')],
                [sg.Canvas(key='controls_cv')],
                [sg.T('Figure:',font='Any 14 bold')],
                    [sg.Column(
                    layout=[
                        [sg.Canvas(key='fig_cv',
                                   size=(300 * 2, 300)
                                   )]
                    ],
                    background_color='#DAE0E6',
                    pad=(0, 0)
                )],
               [sg.B('Exit')] 
               
               ]
    
    window = sg.Window('Data Visualization', layout, finalize=True)
    

    return window


# ------------------------------- Window3 code -------------------------------

def make_win3():
    
    offline = [
        [sg.T('Offline Training', font='Any 16 bold')],
        [sg.T('Please select your input file:', font='Any 12'),sg.Input(key = '-file1-'), sg.FileBrowse()],
        [sg.T('Please select your training model:', font='Any 12'), sg.B('Random Forest Regression Offline', font='Any 12'), sg.B('Gradient Boosting Regression Offline', font='Any 12')],
        [sg.Text('Output value:', font='Any 14 bold'), sg.Text(size=(50,1), font = 'Any 14 bold',text_color='#003366', key='-OUTPUT_off-')],
        [sg.Text('Confidence interval:', font='Any 14 bold'), sg.Text(size=(50,1), font = 'Any 14 bold', text_color='#003366', key='-CI_off-')]
        ]
    
    
    online = [
        [sg.T('Online Training', font='Any 16 bold')],
        [sg.T('Please select your input file:', font='Any 12'),sg.Input(key = '-file2-'), sg.FileBrowse()],
        [sg.T('If you choose Random Forest, please assign variables below:', font='Any 12')],
        [sg.T('N Estimators', font='Any 12'),sg.InputText(key='-R_estimators-')],
        [sg.T('Max features', font='Any 12'),sg.InputText(key='-features-')],
        [sg.T('If you choose Gradient Boosting, please assign variables below:', font='Any 12')],
        [sg.T('N Estimators', font='Any 12'),sg.InputText(key='-G_estimators-')],
        [sg.T('Learning rate', font='Any 12'),sg.InputText(key='-rate-')],
        [sg.T('Max depth', font='Any 12'),sg.InputText(key='-depth-')],
        [sg.T('Please select your training model:', font='Any 12'), sg.B('Random Forest Regression Online',font='Any 12'), sg.B('Gradient Boosting Regression Online', font='Any 12')],
        [sg.Text('Output value:', font='Any 14 bold'), sg.Text(size=(50,1), font = 'Any 14 bold', text_color='#003366', key='-OUTPUT_on-')],
        [sg.Text('Confidence interval:', font='Any 14 bold'), sg.Text(size=(50,1), font = 'Any 14 bold', text_color='#003366', key='-CI_on-')]
        
        
        ]
    
    
    
    layout = [ 
        [sg.Text('Machine Learning', size=(50, 1), justification='center', font=('Any 20 bold'))]]
    layout +=[[sg.TabGroup([[  sg.Tab('Offline training', offline),
                              sg.Tab('Online training', online),]
                              ])],
              [sg.B('Exit')] 
              ]
    
    layout[-1].append(sg.Sizegrip())
    window = sg.Window('Machine Learning', layout,  resizable=True, finalize = True)
    window.set_min_size(window.size)
    
    return window





# ------------------------------- Main event loop -------------------------------

def main():
    window1, window2, window3= make_win1(), None, None     # start off with 1 window open

    while True:             # Event Loop
        window, event, values = sg.read_all_windows()
        if event == sg.WIN_CLOSED or event == 'Exit':
            window.close()
            if window == window2:       # if closing win 2, mark as closed
                window2 = None
            if window ==window3:       # if closing win 3, mark as closed
                window3 = None
            if window == window1:     # if closing win 1, exit program
                break



        if event == 'Visualization' and not window2:
            window2 = make_win2()
        
        if window == window2:
    
            if event == 'EIS':

                # draw_figure_w_toolbar(window['fig_cv'].TKCanvas, Nyquist_plot_UI(values[0]),window['controls_cv'].TKCanvas)
                draw_figure_w_toolbar(window['fig_cv'].TKCanvas, Nyquist_plot_UI(values['-visual_file-']),window['controls_cv'].TKCanvas)
           
            elif event == 'dqdv':

                # draw_figure_w_toolbar(window['fig_cv'].TKCanvas, diff_cap(values[0], int(values['-number-'])),window['controls_cv'].TKCanvas)
                draw_figure_w_toolbar(window['fig_cv'].TKCanvas, diff_cap(values['-visual_file-'], int(values['-number-'])),window['controls_cv'].TKCanvas)
            elif event == 'Cycling':

                # draw_figure_w_toolbar(window['fig_cv'].TKCanvas,cycling_CCCV(values[0], int(values['-number-'])),window['controls_cv'].TKCanvas)
                draw_figure_w_toolbar(window['fig_cv'].TKCanvas,cycling_CCCV(values['-visual_file-'], int(values['-number-'])),window['controls_cv'].TKCanvas)    
            
            elif event == 'Exit' or event == sg.WIN_CLOSED:
                break
            
            
            
            
        if event == 'Machine Learning' and not window3:
            window3 = make_win3()
        
        if window == window3:
            
            if event == 'Random Forest Regression Offline':
                file_off = values['-file1-']
                output_value_off = str(EIS_to_cap_retention_off_rdf(file_off)[0])
                    
                window['-OUTPUT_off-'].update(output_value_off)
                window['-CI_off-'].update('NA')
                    # window['-CI_off-'].update(CI)
                    
            elif event == 'Gradient Boosting Regression Offline':
                file_off = values['-file1-']
                output_value_gbr = str(EIS_to_cap_retention_off_gbr(file_off)[0][0])
                CI_off = str([EIS_to_cap_retention_off_gbr(file_off)[1][0], EIS_to_cap_retention_off_gbr(file_off)[2][0]])
                window['-OUTPUT_off-'].update(output_value_gbr)
                window['-CI_off-'].update(CI_off)
                    
            # elif event == 'Online training':
                
                
            elif event == 'Random Forest Regression Online':
                file_on = values['-file2-']
                N_Estimators_R = int(values['-R_estimators-'])
                Max_features = int(values['-features-'])
                output_value_on = str(EIS_to_cap_retention_onl_rdf(file_on, N_Estimators_R, Max_features)[0])
                window['-OUTPUT_on-'].update(output_value_on)
                window['-CI_on-'].update('NA')
                
            elif event == 'Gradient Boosting Regression Online':
                file_on = values['-file2-']
                N_Estimators_G = int(values['-G_estimators-'])
                Learning_rate = float(values['-rate-'])
                Max_depth = int(values['-depth-'])
                output_value_gbr = str(EIS_to_cap_retention_onl_gbr(file_on, Learning_rate, N_Estimators_G, Max_depth)[0][0])
                CI_on = str([EIS_to_cap_retention_onl_gbr(file_on, Learning_rate, N_Estimators_G, Max_depth)[1][0], EIS_to_cap_retention_onl_gbr(file_on, Learning_rate, N_Estimators_G, Max_depth)[2][0]])
                window['-OUTPUT_on-'].update(output_value_gbr)
                window['-CI_on-'].update(CI_on)
                
                
                
    window.close()

if __name__ == '__main__':
    main()