# %%
# %load_ext autoreload
# %autoreload 2

# %%
import napari
import napari_omaas
from napari_omaas import utils
from napari.utils import nbscreenshot
import numpy as np
from napari_omaas.custom_exceptions import CustomException
import sys
import os
from pathlib import Path
import tempfile


# %%
def show_last_layer(viewer):
    """

    Helper function to hide all layers but last one.

    Parameters
    ----------
    viewer : a viewer instance
        
    """
    for index, layer in enumerate(viewer.layers):
        if index!=(len(viewer.layers)-1):
            layer.visible = False


# %%
# viewer = napari.Viewer(show=False)
viewer = napari.Viewer(show=True)
o = napari_omaas.OMAAS(viewer)
viewer.window.add_dock_widget(o, area='right')

# %%
##################
## SupRep-SQT1 ###
##################

# my_file = r"\\PC160\GroupOdening\OM_data_Bern\raw_data\2024\20241110\Videosdata\20241110_12h-06m-25" #control 4Hz 11.10.24 #7026 SupRep-SQT1 *red only* *done*
# my_file = r"\\PC160\GroupOdening\OM_data_Bern\raw_data\2024\20241110\Videosdata\20241110_12h-20m-25" #carbachol 2.5Hz 11.10.24 #7026 SupRep-SQT1 *red only* *done*


# %%
my_file = "20241110_12h-20m-25"

# %%
freq_estim_condition = "2.5Hz"
# freq_estim_condition = "4Hz"

condition = "carbachol"
# condition = "control"

# illumination_type = "dual_illumination"
illumination_type = "red_only"

# genotype = "WT"
# genotype = "Sham-SQT1"
# genotype = "UT-SQT1"
genotype = "SupRep-SQT1"

# animal_id = str(7028)
# animal_id = str(7004)
# animal_id = str(7009)
animal_id = str(7026)

# %%
 
############# here we create the saving results folder ############# 

# results_folder_name = fr"M:\PhD students\Saranda Nimani\Optical Mapping\SQT-SupRep\APD maps\{genotype}\{freq_estim_condition}\{condition}\{illumination_type}\{animal_id}\{os.path.basename(my_file)}"

# results_folder_name = fr"APD maps\{genotype}\{freq_estim_condition}\{condition}\{illumination_type}\{animal_id}\{os.path.basename(my_file)}"
results_folder_path = Path(tempfile.gettempdir()) / "napari_omaas_sample_data" / "APD_maps_tutorial" / "APD_ROI_Analysis"/ genotype / freq_estim_condition / condition / illumination_type / animal_id / os.path.basename(my_file)
# results_folder_path.mkdir(exist_ok=True)

# results_folder_path = os.path.normpath(results_folder_name)
if not results_folder_path.exists():
    print(f"Creating Folder: \n'{results_folder_path}'\n*Done*.")
    results_folder_path.mkdir(parents=True, exist_ok=True)
else:
    print(f"Folder: \n'{results_folder_path}'\nAlready exists")

# %%
############# here we create a folder to save the mask for segmentation ############# 

mask_folder = results_folder_path / "mask"
if not os.path.exists(mask_folder):
    print(f"Creating Folder: \n'{mask_folder}'\n*Done*.")
    mask_folder.mkdir(parents=True, exist_ok=True)
else:
    print(f"Folder: \n'{mask_folder}'\nAlready exists")

# %%
# # %%capture
# the %%capture command above will hide the ouptut of this cell bc can be very long (only used for the documentation)

try:
    # viewer.open(path=my_file, plugin= "napari-omaas")
    viewer.open_sample('napari-omaas', 'heart_sample_single_illumination')
except Exception as e:
    raise CustomException(e, sys)

# %%
nbscreenshot(viewer)

# %%
viewer.layers[-1].metadata

# %%

my_shape = [np.array([[-27.10448098, 376.83908381],
        [-27.10448098,  67.77374194],
        [272.08514108,  67.77374194],
        [272.08514108, 376.83908381]])]

viewer.add_shapes(my_shape)

o.rotate_l_crop.setChecked(True)
o.crop_from_shape_btn.click() # done


show_last_layer(viewer=viewer)


# this is just to manipulate the viewer by changing the position of the image, zooming it and changing to the first frame
viewer.camera.center = 0.0, 150, 127
viewer.camera.zoom = 2.3
viewer.dims.current_step = (0, 156, 749)


# %%
# # change to tab called "Shapes"
# o.tabs.setCurrentIndex(1)
# o.crop_all_views_and_rotate_btn.click()

# show_last_layer(viewer=viewer)


# %%

my_shape =[np.array([[128.03402574, 142.83315215],
        [128.03402574, 187.82476519],
        [178.56426079, 187.82476519],
        [178.56426079, 142.83315215]])]


viewer.add_shapes(my_shape, name="ROI_1")

o.plot_last_generated_img(shape_indx=1)

# %%
nbscreenshot(viewer)

# %%
# you can call the current clipping values with the following command:
o.double_slider_clip_trace.value()

# %%
clipping_values = (569.5483417085427, 4576.026331658292)  #carbachol 2.5Hz 11.10.24 #7026 SupRep-SQT1 *red only*


o.plot_last_generated_img(shape_indx=1)

o.is_range_clicked_checkbox.setChecked(True)
o.double_slider_clip_trace.setValue(clipping_values)
o.clip_trace_btn.click() 




# %%
show_last_layer(viewer)

# %%
nbscreenshot(viewer)

# %%
# %%capture
# the %%capture command above will hide the ouptut of this cell bc can be very long (only used for the documentation)

curr_imag = viewer.layers[-1]
viewer.layers.selection.active = curr_imag

contrast_kernel = 3
ref_frame = 10
o.pre_smooth_temp.setValue(1)
o.pre_smooth_spat.setValue(1) 
o.c_kernels.setValue(contrast_kernel)
o.ref_frame_val.setText(str(ref_frame))

o.apply_optimap_mot_corr_btn.click()


# %%
# Using slide window method for normalization to detrend the signal
o.data_normalization_options.setCurrentText("Slide window")
o.slide_wind_n.setValue(200)
# o.data_normalization_options.setCurrentText("Local max") # Note: Use when stable traces or when "Slide window" is creating artifacts
o.inv_and_norm_data_btn.click()

o.plot_last_generated_img(shape_indx=1)

# %%
nbscreenshot(viewer)

# %%
o.spat_filter_types.setCurrentText("Median")
o.apply_spat_filt_btn.click()

# %%
o.apply_temp_filt_btn.click()

# %%
o.plot_last_generated_img(shape_indx=1)

# %%
nbscreenshot(viewer)

# %%
show_last_layer(viewer)

# %%
mask_file_path = os.path.join(mask_folder, "Heart_labels_NullBckgrnd.tif")

# %%
# use another image layer to create mask, then use that mask to to apply segmentation to last layer

viewer.layers.selection.active = viewer.layers[5] # take the ratio image normalized
o.return_img_no_backg_btn.setChecked(False)
# o.return_img_no_backg_btn.setChecked(True)
o.apply_auto_segmentation_btn.click()
viewer.layers.select_previous()
o.apply_manual_segmentation_btn.click() # done

# %%
show_last_layer(viewer)

# %%
# save Mask if newly created
try:
    print(f"Saving mask to: \n'{mask_file_path}'\n*Done*.")
    viewer.layers[-1].save(mask_file_path)
except Exception as e:
    CustomException(e, sys)

# %%
# curr_imag = viewer.layers[-1]


# try:
#     viewer.open(mask_file_path)
# except Exception as e:
#     CustomException(e, sys)

# viewer.layers.selection.active = curr_imag
# o.apply_manual_segmentation_btn.click() # done
# dont forget to change mask folder!

# %%
APD_ROIs = [
        np.array([[69.71631372, 38.57159234],
              [69.71631372, 53.11573853],
              [85.42399161, 53.11573853],
              [85.42399161, 38.57159234]]),
        np.array([[165.70767858,  42.06218743],
                [165.70767858,  56.60633362],
                [181.41535646,  56.60633362],
                [181.41535646,  42.06218743]]),
        np.array([[230.28368766,  71.15047981],
                [230.28368766,  85.694626  ],
                [245.99136555,  85.694626  ],
                [245.99136555,  71.15047981]]),
        np.array([[ 76.11573805, 181.10422501],
                [ 76.11573805, 195.6483712 ],
                [ 91.82341593, 195.6483712 ],
                [ 91.82341593, 181.10422501]]),
        np.array([[161.63531765, 176.45009823],
                [161.63531765, 190.99424442],
                [177.34299553, 190.99424442],
                [177.34299553, 176.45009823]]),
        np.array([[232.02898521, 147.36180585],
                [232.02898521, 161.90595204],
                [247.73666309, 161.90595204],
                [247.73666309, 147.36180585]])
        ]

RV, LV = ["Right ventricle" for i in range(0,3)], ["Left ventricle" for i in range(0,3)]
RV_id, LV_id = [f"RV_{i}" for i in range(0,3)], [f"LV_{i}" for i in range(0,3)]
heart_view = ["Anterior" for i in range(0,6)]
position = ["Base", "Middle", "Apex"]

features = {
    'ID':RV_id + LV_id,
    'region':RV + LV,
    'panView': heart_view,
    'position':position + position
}


edge_color_cycle = ['magenta', 'blue']

text = {
    'string': '{ID}: {region}\nPosition: {position}\nView: {panView}',
    'anchor': 'upper_left',
    'translation': [0, 0],
    'size': 15,
    'color': 'black',
}



viewer.add_shapes(
    APD_ROIs,
    text = text, 
    features=features,
    edge_color='region',
    face_color='transparent',
    edge_color_cycle=edge_color_cycle,
    edge_width=2
    )

# %%
nbscreenshot(viewer)

# %%
o.tabs.setCurrentIndex(4)

# %%
o.plot_last_generated_img(shape_indx=2)

# %%
o.compute_APD_btn.click()

# %%
nbscreenshot(viewer)

# %%
o.APD_rslts_dir_box_text.setText(str(results_folder_path)) # uncomment this to save the files directly on the current results folder
o.save_APD_rslts_btn.click()
