from java.awt import BorderLayout, GridLayout
from javax.swing import JFrame, JPanel, JLabel, JButton, ImageIcon, JComboBox
from ij import IJ
from ij.plugin.frame import Recorder
import os
import java.lang.Exception

# Kevin Terretaz march 2023
# 2.1 Thanks to Nicolás De Francesco, the LUTs categories are cleaner so you can select them with keyboard 
# LUT Panel inspired by Jan Brocher's LUT channel Tool from the Biovoxxel Figure Tool update site
# https://github.com/biovoxxel/BioVoxxel-Figure-Tools/blob/main/biovoxxel-figure-tools/src/main/java/lut/tool/LutChannelsTool.java 

class lut_Panel(JFrame):
	def __init__(self):
		# main window
		super(lut_Panel, self).__init__("NeuroCytoLUTs")
		self.setLayout(BorderLayout())

		# top panel LUT folders list
		self.top_panel = JPanel()
		self.top_panel.add(JLabel("Select a LUT folder : "))
		self.lut_folder_names, self.lut_folders = zip(*get_LUT_folders_list())
		self.combobox = JComboBox(self.lut_folder_names)
		self.combobox.addActionListener(self.update_LUTs)
		self.top_panel.add(self.combobox)
		self.add(self.top_panel, BorderLayout.NORTH)
		
		#make LUT buttons panel
		self.lut_panel = self.make_LUT_Panel("", True)

		# create and show main window
		self.add(self.lut_panel, BorderLayout.CENTER)
		self.setLocationRelativeTo(None)  # center in the screen
		self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
		self.pack()
		self.setVisible(True)
		
	def make_LUT_Panel(self, path, main):
		if main == True :
			script_List = get_main_scripts()
		else :
			script_List = get_script_paths_recursively(path)
		# Create LUT icon and buttons
		lut_panel = JPanel()
		lut_panel.setLayout(GridLayout(0, 6, 2, 2)) # 6 columns, 2px gap between components
		lut_Image = IJ.createImage("LUT icon", "8-bit ramp", 64, 25, 1)
		for script_path in script_List:
			lut_script = IJ.openAsString(str(script_path))
			IJ.redirectErrorMessages() #Avoid error popup dialog in case of missing LUT file
			try:
				IJ.run(lut_Image, lut_script[5:-4], "")
			except java.lang.Exception as e:
				continue #jump to next loop
			awt_icon_Image = ImageIcon(lut_Image.getImage())
			button = JButton(name=str(lut_script), toolTipText=str(lut_script[5:-4]), actionPerformed=self.apply_LUT, icon=awt_icon_Image)
			lut_panel.add(button)
		return lut_panel
	
	def apply_LUT(self, event):
		# extract lut_script from Button Name
		text = (event.getSource()).getName()
		IJ.runMacro(text)
		Recorder.recordString(text)

	def update_LUTs(self, event):
		# Clear the panel and add a new button
		self.remove(self.lut_panel)
		folder = self.lut_folders[self.lut_folder_names.index(self.combobox.getSelectedItem())]
		path = IJ.getDirectory("imageJ") + "/scripts/LUTs/" + folder
		self.lut_panel = self.make_LUT_Panel(path, False)
		self.add(self.lut_panel, BorderLayout.CENTER)
		self.pack()

def get_script_paths_recursively(main_folder):
	script_list = []
	for root, sub_folders, files in os.walk(main_folder):
		for file in files:
			script_list.append(os.path.join(root, file))
	return script_list

def get_main_scripts(): 
	script_list = []
	for item in os.listdir(IJ.getDirectory("imageJ") + "/scripts/LUTs/"):
		path = os.path.join(IJ.getDirectory("imageJ") + "/scripts/LUTs/", item)
		if not os.path.isdir(path) and str(item).startswith("_") :
			script_list.append(path)
	return sorted(script_list, cmp=custom_sort)
	
def get_LUT_folders_list():
	lut_folders = []
	for item in os.listdir(IJ.getDirectory("imageJ") + "/scripts/LUTs/"):
		if os.path.isdir(os.path.join(IJ.getDirectory("imageJ") + "/scripts/LUTs/", item)):
			lut_folders.append((item.replace("_"," ").strip(), item))
	return sorted(lut_folders, cmp=custom_sort, key=lambda folder: folder[1])

def custom_sort(string_1, string_2): # to put underscores first...
	if string_1.count("_") > string_2.count("_"):
		return -1
	else:
		return string_1.lower() < string_2.lower()

lut_Panel()