'''
ID: IMPORTS
Code block: import statemants.
'''

import ipywidgets as ipw
import geomacc as gma
from pandas import set_option as set_option
from pprint import pprint

get_ipython().run_line_magic("matplotlib", " widget")


'''
ID: DEFAULT APP LAYOUT
Codeblock: default objects of main window are defined
    here. Mainly for development purposes.

## Docasna definice boxu v AppLayout
Abych si na zacatku mel vubec co zobrazit,
definuju si tady (zbytecnou) funkci pro
vyrobu tlacitek a nasledne tlacitka, kterymi
zaplnim prostor v AppLayout.
'''

def create_button(description, button_style):
    return ipw.Button(
        description=description,
        button_style=button_style,
        layout=ipw.Layout(height='auto', width='auto'),)

header = create_button("Here shall be the HEADER", 'info')
footer = create_button("FOOTER", 'info')
left = create_button("LEFT PANE", 'success')
right = create_button("RIGHT PANE", 'danger')

with open("images/mesh_surface_low_res.jpg", "rb") as f:
    center_image = f.read()
center = ipw.Image(
    value=center_image,
    format='jpg',
    width='auto',
    height='auto',
)


'''
ID: MAIN BOX - HEADER
Code block: V tomto bloku je kompletni definice okna header
    na pozici header v main boxu.

## DEFINICE 'HEADER' V MAIN_BOX

V teto bunce je definovana konecna podoba headeru.
'''

# Docasna podoba - TO DO HERE
file_header = open('images/header.png', 'rb')
image_header = file_header.read()

header_box_layout = ipw.Layout(
    display='flex',
    flex_flow='column',
    align_items='stretch',
    width='100get_ipython().run_line_magic("',", "")
    height='100get_ipython().run_line_magic("',", "")
    border='solid 1px',
    grid_area='header',
)
header_box = ipw.Image(
    value=image_header,
    format='png',
    width='auto',
    height=44,
    layout=header_box_layout
)


'''
ID: MAIN BOX - FOOTER
Code block: V tomto bloku je kompletni definice okna footer
    na pozici footer v main boxu.

## DEFINICE 'FOOTER' V MAIN_BOX

V teto bunce je definovana konecna podoba footer.
'''

# Docasna podoba - TO DO HERE
file_footer = open('images/footer.png', 'rb')
image_footer = file_footer.read()

footer_box_layout = ipw.Layout(
    display='flex',
    flex_flow='column',
    align_items='stretch',
    width='100get_ipython().run_line_magic("',", "")
    height='100get_ipython().run_line_magic("',", "")
    border='solid 1px',
    grid_area='footer',
)
footer_box = ipw.Image(
    value=image_footer,
    format='png',
    width='auto',
    height='auto',
    layout=footer_box_layout
)


'''
ID: MAIN BOX - LEFT SIDEBAR
Code block: V tomto bloku je kompletni definice okna left sidebar
    na pozici left sidebar v main boxu.

## DEFINICE LEFT_BOX NA POZICI LEFT_SIDEBAR V APPLAYOUT

V teto bunce je definovana konecna podoba okna LEFT_BOX.
'''
button_lb_home = ipw.Button(
    description='Home Screen',
    disabled=False,
    button_style='', # 'success', 'info', 'warning', 'danger' or ''
    tooltip='Go to home screen for initial information.',
    icon='home',
)

button_lb_data_load = ipw.Button(
    description='Data Load',
    disabled=False,
    button_style='', # 'success', 'info', 'warning', 'danger' or ''
    tooltip='Load data from file <name>.rtl exported from "Carto Explore"',
    icon='folder',
)

button_lb_data_view = ipw.Button(
    description='Data View',
    disabled=False,
    button_style='',
    tooltip='View imported data. Filtr, what should be calculated.',
    icon='table',
)

button_lb_compute = ipw.Button(
    description='Compute',
    disabled=False,
    button_style='',
    tooltip='Compute geometric accuracy data/statistics.',
    icon='bar-chart',
)

button_lb_compensate = ipw.Button(
    description='Compensate',
    disabled=False,
    button_style='',
    tooltip='Compute compensation table and export it to machine ready file.',
    icon='calculator',
)

button_lb_history = ipw.Button(
    description='History',
    disabled=False,
    button_style='',
    tooltip='Browse history.',
    icon='history',
)

out = ipw.Output()

def home_on_click(_):
    with out:
        #update_main_box(center=window_data_load)
        update_main_box(position='center', new_window=window_home)
        
def data_load_on_click(_):
    with out:
        #update_main_box(center=window_data_load)
        update_main_box(position='center', new_window=window_data_load)

def data_view_on_click(_):
    with out:
        #update_main_box(center=window_data_view)
        update_main_box(position='center', new_window=window_data_view)

def compute_on_click(_):
    with out:
        #update_main_box(center=window_compute)
        update_main_box(position='center', new_window=window_compute)

def compensate_on_click(_):
    with out:
        #update_main_box(center=window_compensate)
        update_main_box(position='center', new_window=window_compensate)

def history_on_click(_):
    with out:
        #update_main_box(center=window_history)
        update_main_box(position='center', new_window=window_history)


#button_lb_data_load.on_click(update_main_box_on_click(window_data_load))
button_lb_home.on_click(home_on_click)
button_lb_data_load.on_click(data_load_on_click)
button_lb_data_view.on_click(data_view_on_click)
button_lb_compute.on_click(compute_on_click)
button_lb_compensate.on_click(compensate_on_click)
button_lb_history.on_click(history_on_click)

# Konstrukce left_box, ktery je umisten v left_sidebar.
left_box_layout = ipw.Layout(
    display='flex',
    flex_flow='column',
    overflow='auto',
    align_items='stretch',
    width='160px',
    height='100get_ipython().run_line_magic("',", "")
    grid_area='left_sidebar',
)

left_box = ipw.VBox(
    [
        button_lb_home,
        button_lb_data_load,
        button_lb_data_view,
        button_lb_compute,
        button_lb_compensate,
        button_lb_history,
    ],
    layout=left_box_layout,
)


'''
ID: CENTER = HOME
Code block: V tomto bloku je kompletni definice PODokna Home Screen
    na pozici center v main boxu.

## DEFINICE OKNA NA POZICI CENTER PRO HOME

V teto bunce je definovana konecna podoba okna DATA LOAD.
'''

window_home = ipw.Image(
    value=center_image,
    format='jpg',
    width='auto',
    height='auto',
)


'''
ID: CENTER = DATA LOAD
Code block: V tomto bloku je kompletni definice PODokna Data Load
    na pozici center v main boxu.

## DEFINICE OKNA NA POZICI CENTER PRO DATA LOAD

V teto bunce je definovana konecna podoba okna DATA LOAD.
'''

# Docasna podoba - TO DO HERE
button_data_load_1 = ipw.Button(
    description='Load File',
    disabled=False,
    button_style='',
    tooltip='Opens up a browse window to locate <name>.rtl file.',
    icon='file',
)

button_data_load_1_out = ipw.Output()

def button_data_load_1_click(_):
    
    '''
    def do():
        global from_path
        from_path = gma.core.dialog()
        to_path = './geomacc/.working_folder/raw.csv'
        gma.core.readFromRTL.extract(
            from_path,
            to_path,
            'Run Target Data:',
            '\n',
        )
    '''
    
    source_path = gma.core.dialog()
    global varfile_str, varfile_list
    varfile_str, varfile_list = gma.core.load_into_var(source_path)
    
    def load_to_df():
        Norm_0.data_raw = gma.core.ReadFromRTL.extract_section(
            varfile_list,
            'Run Target Data:',
            '\n',
        )
        data_df = gma.core.load_to_df(Norm_0.data_raw)
        return data_df
    
    Norm_0.tabulka= load_to_df()
    set_option('display.max_rows', 999)
    set_option('display.min_rows', 30)
    button_data_load_1_out.clear_output()
    
    with button_data_load_1_out:
        print("Data successfully loaded")
        display(Norm_0.tabulka)

button_data_load_1.on_click(button_data_load_1_click)

windows_data_load_layout = ipw.Layout(
    display='flex',
    flex_flow='row',
    align_items='stretch',
    width='100get_ipython().run_line_magic("',", "")
    height='100get_ipython().run_line_magic("',", "")
    border='solid 1px',
    grid_area='center',
)
window_data_load = ipw.Box([
    ipw.HBox([
        button_data_load_1,
        #button_data_load_1,
        button_data_load_1_out,
    ], layout=windows_data_load_layout)
])


'''
ID: CENTER = DATA VIEW
Code block: V tomto bloku je kompletni definice PODokna Data View
    na pozici center v main boxu.

## DEFINICE OKNA NA POZICI CENTER PRO DATA VIEW

V teto bunce je definovana konecna podoba okna DATA VIEW.
'''

# Docasna podoba - TO DO HERE
'''
window_data_view = ipw.Button(
    description='Data View Window.',
    disabled=False,
    button_style='',
    tooltip='Browse history.',
    icon='victory',
)
'''
window_data_view = ipw.Textarea(
    value='Tady bude okno pro interaktivni prohlizeni \
    nactenych dat. Bude mozne hodnoty seskupovat, filtrovat \
    mozna i editovat.',
    description='TO DO:',
    disabled=False
)


'''
ID: COMPUTE HEADER
Code block: V tomto bloku je kompletni definice PODokna Header
    na pozici header okna Compute, ktere je na pozici center
    v main boxu.
'''


compute_header_status = ipw.Text(
    value='Ready',
    placeholder='',
    description='Computation Status:',
    disabled=False,
)


### BUTTON START
button_compute_header_run = ipw.Button(
    description='Run',
    disabled=False,
    button_style='', # 'success', 'info', 'warning', 'danger' or ''
    tooltip='Run the calculation.',
    icon='',
)


def button_compute_run_onclick(b):
    compute_proccess()
    with out_iso230x2x2014:
        display(Norm_0.fig)
    with out_iso230x2x2014:
        pprint(Norm_0.stats.main_stats)
    update_iso230x2x2014(out_iso230x2x2014)


button_compute_header_run.on_click(button_compute_run_onclick)
### BUTTON END


compute_header_layout = ipw.Layout(
    display='flex',
    flex_flow='row',
    align_items='stretch',
    width='100get_ipython().run_line_magic("',", "")
    height='100get_ipython().run_line_magic("',", "")
    border='solid 1px',
    grid_area='compute_header',
)

compute_header = ipw.HBox([
    compute_header_status,
    button_compute_header_run,
    ], layout=compute_header_layout,
)


'''
ID: COMPUTE LEFT SIDEBAR
Code block: V tomto bloku je kompletni definice PODokna Left Sidebar
    na pozici left sidebar okna Compute, ktere je na pozici center
    v main boxu.
'''

compute_left_sidebar_iso230_2 = ipw.Button(
    description='ISO 230-2:2014',
    disabled=False,
    button_style='', # 'success', 'info', 'warning', 'danger' or ''
    tooltip='Calculation according to ISO 230-2:2014',
    icon='lightbulb-o',
)


def update_compute_center(**kwargs):
    set_position = kwargs['position']
    set_new_window = kwargs['new_window']
    '''
    V nasledujici IF funkci odpovidaji prirazena
    cisla radkum v definici main_box:
        0 = 0. radek = compute_header
        1 = 1. radek = compute_left_sidebar
        2 = 2. radek = compute_center
    '''
    if set_position == 'header': i = 0
    elif set_position == 'left_sidebar': i = 1
    elif set_position == 'center': i = 2
    temp = list(window_compute.children)
    temp[i] = set_new_window
    window_compute.children = tuple(temp)
    display(window_compute)


def compute_left_sidebar_iso230_2_onclick(_):
    update_compute_center(position='center', new_window=compute_center_iso230x2x2014)

    
compute_left_sidebar_iso230_2.on_click(compute_left_sidebar_iso230_2_onclick)

compute_left_sidebar_layout = ipw.Layout(
    display='flex',
    flex_flow='row',
    align_items='stretch',
    width='100get_ipython().run_line_magic("',", "")
    height='100get_ipython().run_line_magic("',", "")
    border='solid 1px',
    grid_area='compute_left_sidebar',
)
compute_left_sidebar = ipw.VBox(
    [
        compute_left_sidebar_iso230_2
    ],
    layout=compute_left_sidebar_layout,
)



'''
ID: COMPUTE CENTER iso230x2x2014
Code block: V tomto bloku je kompletni definice PODokna Center
    pro normu iso230x2x2014
    na pozici center okna Compute, ktere je na pozici center
    v main boxu.
'''


# TO DO get_ipython().getoutput("!!!!!!!!!!!")
# norm0 je identifikator pro normu iso 230-2:2014
# presunout nekam do samostatne bunky
class Norm_0(object):
    """
    Container for variables only = NAMESPACE HERE
    """
    pass


def compute_proccess():
    # namerena data
    Norm_0.meta_data = gma.core.MetaDictConst.const_measure_data(varfile_list)
    Norm_0.runs_all, Norm_0.runs_odd, Norm_0.runs_even = gma.core.run_all(Norm_0.tabulka, Norm_0.meta_data)
    Norm_0.fig = gma.core.figs(Norm_0.runs_all, Norm_0.meta_data)

    # vypocet dle normy
    Norm_0.stats = gma.norms.DefineData(
        Norm_0.meta_data['Run-count'],
        Norm_0.meta_data['Target-count'],
    )
    # Norm_0.stats.transformTable(Norm_0.data_raw)
    # Norm_0.stats.load_data(source='var', value=Norm_0.tabulka)
    Norm_0.stats.preprocess_data(Norm_0.tabulka)
    Norm_0.stats.def_all()
    Norm_0.stats.main_stats()


out_iso230x2x2014 = ipw.Output(layout={'border': '1px solid black'})


compute_center_test = ipw.Text(
    value='Ready',
    placeholder='',
    description='Computation Status:',
    disabled=False,
)


def update_iso230x2x2014(new_window):
    '''
    compute_center_iso230x2x2014:
    0 = 0. radek = compute_header
    '''
    temp = list(compute_center_iso230x2x2014.children)
    temp[0] = new_window
    compute_center_iso230x2x2014.children = tuple(temp)
    display(compute_center_iso230x2x2014)

    
compute_center_iso230x2x2014_layout = ipw.Layout(
    display='flex',
    flex_flow='row',
    align_items='stretch',
    width='100get_ipython().run_line_magic("',", "")
    height='100get_ipython().run_line_magic("',", "")
    border='solid 1px',
    grid_area='compute_center',
)

compute_center_iso230x2x2014 = ipw.VBox(
    [
        compute_center_test
    ],
    layout=compute_center_iso230x2x2014_layout,
)



'''
ID: COMPUTE CENTER
Code block: V tomto bloku je kompletni definice PODokna Center
    na pozici center okna Compute, ktere je na pozici center
    v main boxu.
'''

with open("images/mesh_surface_low_res.jpg", "rb") as fx:
    center_imagex = fx.read()
compute_center = ipw.Image(
    value=center_imagex,
    format='jpg',
    width='auto',
    height='auto',
    grid_area='compute_center',
)


'''
ID: CENTER = COMPUTE
Code block: V tomto bloku je kompletni definice PODokna Compute
    na pozici center v main boxu.

## DEFINICE OKNA NA POZICI CENTER PRO COMPUTE

V teto bunce je definovana konecna podoba okna COMPUTE.
'''

'''
# Docasna podoba - TO DO HERE
window_compute = ipw.Button(
    description='Compute Window.',
    disabled=False,
    button_style='',
    tooltip='Browse history.',
    icon='victory',
)
'''

window_compute_layout = ipw.Layout(
    height='100%',  # viewport height, 1vh = 1% of browser’s heightget_ipython().getoutput("!!!!!!!!!!")
    width='100get_ipython().run_line_magic("',", "")
    grid_gap='5px',
    overflow='auto',
    overflow_x='auto',
    align_items='stretch',
    #align_content='stretch',
    margin='0px',
    border='0px',
    padding='0px',
    display='grid',
    grid_template_rows='5% 95get_ipython().run_line_magic("',", "")
    grid_template_columns='10% 90get_ipython().run_line_magic("',", "")
    grid_template_areas='''
        "compute_left_sidebar compute_header"
        "compute_left_sidebar compute_center"
    ''',
    grid_area='center',  # toto okno se vykresluje na pozici 'center'
)

window_compute = ipw.GridBox(
    children=[
        compute_header,
        compute_left_sidebar,
        compute_center,
    ],
    layout=window_compute_layout,
)


'''
ID: CENTER = COMPENSATE
Code block: V tomto bloku je kompletni definice PODokna Compensate
    na pozici center v main boxu.

## DEFINICE OKNA NA POZICI CENTER PRO COMPENSATE

V teto bunce je definovana konecna podoba okna COMPENSATE.
'''

# Docasna podoba - TO DO HERE
window_compensate = ipw.Button(
    description='Compensate Windows.',
    disabled=False,
    button_style='',
    tooltip='Browse history.',
    icon='victory',
)


'''
ID: CENTER = HISTORY
Code block: V tomto bloku je kompletni definice PODokna History
    na pozici center v main boxu.

## DEFINICE OKNA NA POZICI CENTER PRO HISTORY

V teto bunce je definovana konecna podoba okna HISTORY.
'''

# Docasna podoba - TO DO HERE
window_history = ipw.Button(
    description='History Window.',
    disabled=False,
    button_style='',
    tooltip='Browse history.',
    icon='victory',
)


'''
ID: MAIN BOX DEFINITION
Code block: V tomto bloku je konstrukce hlavniho okna (main box)
    a pomocne funkce pro jeho chod.

## KONSTRUKCE A DEFINICE HLAVNIHO OKNA APPLAYOUT


'''
'''
main_box_layout = ipw.Layout(
    #height='1080px',
    #width='1920px',
    height='900px',
    width='100get_ipython().run_line_magic("',", "")
    grid_gap='0px',
    overflow='auto',
    #align_items='stretch',
    #align_content='stretch',
)

# Docasna podoba - TO DO HERE
main_box = ipw.AppLayout(
    header=header_box,
    footer=footer_box,
    center=center,
    left_sidebar=left_box,
    right_sidebar=None,
    layout=main_box_layout,
)
'''

main_box_layout = ipw.Layout(
    height='96vh',  # viewport height, 1vh = 1% of browser’s heightget_ipython().getoutput("!!!!!!!!!!")
    width='99.5get_ipython().run_line_magic("',", "")
    grid_gap='5px',
    overflow='visible',
    align_items='stretch',
    #align_content='stretch',
    margin='0px',
    border='0px',
    padding='0px',
    display='grid',
    grid_template_rows='5% 90% 3get_ipython().run_line_magic("',", "")
    grid_template_columns='8% 92get_ipython().run_line_magic("',", "")
    grid_template_areas='''
        "header header"
        "left_sidebar center"
        "footer footer"
    ''',
)

main_box = ipw.GridBox(
    children=[
        header_box,
        footer_box,
        left_box,
        center,
    ],
    layout=main_box_layout,
)

display(main_box)

'''
def update_main_box(**kwargs):
    for item in kwargs.items():
        key, value = item
    setattr(main_box, key, value)
'''

def update_main_box(**kwargs):
    set_position = kwargs['position']
    set_new_window = kwargs['new_window']
    '''
    V nasledujici IF funkci odpovidaji prirazena
    cisla radkum v definici main_box:
        0 = 0. radek = header_box
        1 = 1. radek = footer_box
        2 = 2. radek = left_box
        3 = 3. radek = center
    '''
    if set_position == 'header': i = 0
    elif set_position == 'footer': i = 1
    elif set_position == 'left_sidebar': i = 2
    elif set_position == 'center': i = 3
    temp = list(main_box.children)
    temp[i] = set_new_window
    main_box.children = tuple(temp)
    display(main_box)



