#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 14 15:54:49 2022

@author: emilydu
"""



__version__ = '0.0.3'
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)


# ------------------------------- 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 Echem Visualizer',size=(40, 1), justification='center', font='Any 20')],
              [sg.Text('Please select one to start:', font='Any 14')],
              [sg.Column(buttons)]
              ]
   
    window = sg.Window('Echem Visualizer', layout, finalize=True, margins=(20, 20))
    # window.set_min_size(window.size)
    
    return window




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


def make_win2():


    top_col = [
        [sg.T(
'''This program allows the user to plot three different forms of electrochemistry data. The ploted figure can then be adjusted and exported as needed.
These are the supported file types:
    - Auto-lab EIS data
    - Battery cycling data''', font='Any 12')],
    
                
[sg.T('''User instruction: ''', font='Any 12 bold')],

    [sg.T('''    - EIS plot: Please import your auto-lab EIS file only (other files will not be supported!). Leave the cycling number blank.
    - dQ/dV plot: Please import your cycling data and specify the cycling number.
    - Cycling plot: Please import your cycling data and specify the cycling number.
After importing the data, please click on the plot type. Figure will be shown below with a control panel.''',
             font='Any 12')], #title name
        # [sg.T('')],
        [sg.T('Please select your input file:', font='Any 12 bold'),sg.Input(key='-visual_file-', size=(80, 1)), sg.FileBrowse(font='Any 12')], #file browse
                [sg.T('Cycle Number', font='Any 12 bold'),sg.InputText(key='-number-', size=(80, 1)), sg.T('(Integer Only)') ], #cycle number
                [sg.T('Please select the plot type:', size=(80, 1), font='Any 12 bold')], 
                [sg.Button('EIS', size=(10,1), font='Any 13 bold'), sg.B('dQ/dV', size=(10,1),font='Any 13 bold'), sg.B('Cycling', size=(10,1),font='Any 13 bold')]
                           
                ]



    layout = [ 
        [sg.T('Data Visualization', size=(50, 1), justification='center', font='Any 24 bold')],
               [sg.Column(top_col, element_justification='left')], 
               [sg.T('Control 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('Echem Visualizer', layout, finalize=True)
    

    return window


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

def make_win3():
    
    offline = [
        [sg.T('Offline Training', font='Any 16 bold')],
        [sg.T('''Offline training model is based on 40 Samsung NMC 111/graphite fuel cell batteries from the UW Schmartz Lab. 
The program enables the user to predict capacity retention after 200 cycles based on early cycle impedance data.

Offline training enables the user to do a quick capacity classification on the battery grade based on the first 10 cycles of impedance data.''', font='Any 12')],
[sg.T('User instruction:', font = 'Any 12 bold')],
[sg.T('''    - Please select your input data file (auto-lab EIS only!).
    - Please select the desired training model.
    
Capacity retention will be returned with the confidence interval (as a percentage).
''', font='Any 12')],
        [sg.T('Input data file:', font='Any 12 bold'),sg.Input(key = '-file1-'), sg.FileBrowse(font='Any 12')],
        [sg.T('Please select your training model:', font='Any 12 bold'), sg.B('Random Forest Regression Offline', font='Any 13 bold'), sg.B('Gradient Boosting Regression Offline', font='Any 13 bold')],
        [sg.Text('Capacity rentention:', font='Any 14 bold'), sg.Text(size=(15,1), font = 'Any 14 bold',text_color='#003366', key='-OUTPUT_off-'), sg.T('%',font = 'Any 14 bold',text_color='#003366' )],
        [sg.Text('Confidence interval:', font='Any 14 bold'), sg.Text(size=(15,1), font = 'Any 14 bold', text_color='#003366', key='-CI_off-'),  sg.T('%',font = 'Any 14 bold',text_color='#003366')]
        ]
    
    
    online = [
        [sg.T('Online Training', font='Any 16 bold')],
        [sg.T('''Online training enables user to explore the machine learning parameters using the 40 Samsung NMC 111/graphite full cell batteries 
from the UW Schmartz Lab.''', font='Any 12')],
[sg.T('User instruction:', font = 'Any 12 bold')],
[sg.T('''    - Please select your input data file (auto-lab EIS only!).
    - Follow the steps below:
        - Random Forest: please specify N estimators and max features.
        - Gradient Boosting: please specify N estimators, learning rate, and max depth.
        
Capacity retention will be returned with the confidence interval (as a percentage).
''', font='Any 12')],

        [sg.T('Input data file:', font='Any 12'),sg.Input(key = '-file2-'), sg.FileBrowse(font='Any 12')],
        [sg.T('If you choose Random Forest, please assign variables below:', font='Any 12 bold')],
        [sg.T('N estimators', font='Any 12'),sg.InputText(key='-R_estimators-'), sg.T('(Integer Only)') ],
        [sg.T('Max features', font='Any 12'),sg.InputText(key='-features-'),  sg.T('(Integer Only)')],
        [sg.T('If you choose Gradient Boosting, please assign variables below:', font='Any 12 bold')],
        [sg.T('N estimators', font='Any 12'),sg.InputText(key='-G_estimators-'), sg.T('(Integer Only)')],
        [sg.T('Learning rate', font='Any 12'),sg.InputText(key='-rate-'),  sg.T('(Between 0.01 to 0.1)')],
        [sg.T('Max depth', font='Any 12'),sg.InputText(key='-depth-'), sg.T('(Integer Only)')],
        [sg.T('Please select your training model:', font='Any 12'), sg.B('Random Forest Regression Online',font='Any 13 bold'), sg.B('Gradient Boosting Regression Online', font='Any 13 bold')],
        [sg.Text('Capacity rentention:', font='Any 14 bold'), sg.Text(size=(20,1), font = 'Any 14 bold', text_color='#003366', key='-OUTPUT_on-'), sg.T('%',font = 'Any 14 bold',text_color='#003366' )],
        [sg.Text('Confidence interval:', font='Any 14 bold'), sg.Text(size=(20,1), font = 'Any 14 bold', text_color='#003366', key='-CI_on-'), sg.T('%',font = 'Any 14 bold',text_color='#003366' )]
        
        
        ]
    
    
    
    layout = [ 
        [sg.Text('Machine Learning', size=(50, 1), justification='center', font=('Any 24 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('Echem Visualizer', 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 == 'dQ/dV':
                # 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))
                    
                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])
                lower_off = EIS_to_cap_retention_off_gbr(file_off)[1]
                upper_off = EIS_to_cap_retention_off_gbr(file_off)[2]
                CI_off = str([ lower_off, upper_off])
                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))
                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-'])
                lower_on = EIS_to_cap_retention_onl_gbr(file_on, Learning_rate, N_Estimators_G, Max_depth)[1]
                upper_on = EIS_to_cap_retention_onl_gbr(file_on, Learning_rate, N_Estimators_G, Max_depth)[2]
                output_value_gbr = str(EIS_to_cap_retention_onl_gbr(file_on, Learning_rate, N_Estimators_G, Max_depth)[0])
                CI_on = str([ lower_on, upper_on])
                window['-OUTPUT_on-'].update(output_value_gbr)
                window['-CI_on-'].update(CI_on)
                
                
                
    window.close()

if __name__ == '__main__':
    main()