"""
Inscoper API Example Script: Z-Stack Acquisition
================================================
This script performs a Z-stack acquisition using a list of Status states.

Configuration Prerequisites:
---------------------------
1. Environment Variable: Ensure 'InscoperConfigsPath' is defined in your environment
   and points to your Inscoper configurations folder.
2. Configuration Name: This script assumes a hardware configuration named "camera_and_microscope_and_fluo_source".
   Change it below if your configuration is named differently.
3. Device/Channel Names: Customize device and focus sub-device names below.
"""
import os
from typing import Dict
from dataclasses import dataclass
import numpy as np
import matplotlib.pyplot as plt
import inscoper_api


@dataclass
class SubDevice:
    name: str = None # a descriptive string for the sub-device
    tag: int = None # a unique identifier within the device for this sub-device
    inscoper_type: int = None # a "purpose" type for the sub-device (what it does, e.g., CUBE, OBJECTIVE, SHUTTER...)

@dataclass
class Device:
    name: str # the name given to the device during the configuration step
    hardware_id: int # an identifier for this device model
    sub_device_map: Dict[int, SubDevice] # the collection of chosen sub-devices for this particular device instance

class CustomImageListener(inscoper_api.ImageListener):
    def __init__(self):
        super().__init__()
        self._received_images = []
        self._image_counter = 0

    def handleNewImage(self, image):
        print(f"Image {self._image_counter} received!")
        self._image_counter += 1
        self._received_images.append(image)

    def getReceivedImages(self):
        return self._received_images

# Macro to all Inscoper configurations
CONFIG_PATH = os.environ['InscoperConfigsPath']

my_bridge = inscoper_api.Bridge()
my_listener = CustomImageListener()
my_bridge.addImageListener(my_listener)

config = my_bridge.readConfigFile(os.sep.join([CONFIG_PATH, "camera_and_microscope_and_fluo_source"]))
my_bridge.loadConfigFile(os.sep.join([CONFIG_PATH, "camera_and_microscope_and_fluo_source"]))
my_bridge.initDevices()

# Dictionary to store the mapping of hardware IDs to our Device objects.
device_map = {}

# Step 0: Iterate over the "Device List" from the configuration. 
# This tells us what specific devices have been added to this system's configuration.
for device in config.getDeviceList():
    driver_config = device.getDriverConfig()
    
    # In this example, we only keep devices controlled by the Inscoper Device Controller.
    if isinstance(driver_config, inscoper_api.InscoperBoxDriverConfig):
        device_name = device.getId() # e.g., "My Microscope" or "My Stage"
        device_id = driver_config.getHardwareId() # The internal hardware identifier

        sub_device_map = {}
        
        # Iterate over all sub-devices configured for this device.
        for sub_device_config in device.getSubDeviceConfigList():
            sub_device_tag = sub_device_config.getTag() # The unique tag will allow us to connect config and description
            sub_device_id = sub_device_config.getId() # Descriptive name of the sub-device
            
            # Create our SubDevice instance and map it by its tag.
            sub_device_map[sub_device_tag] = SubDevice(name=sub_device_id, tag=sub_device_tag)
            
        # Store the complete Device object (with its sub-devices) in our global map.
        device_map[device_id] = Device(name=device_name, hardware_id=device_id, sub_device_map=sub_device_map)

# At this point, device_map contains our devices, but we are missing the "purpose" of each sub-device.
print(device_map)

# Step 0: Iterate over the "Device Description List".
# This information acts as the "class definitions" (descriptions.xml) for all possible hardware supported by Inscoper,
# providing metadata like the generic type (purpose) of the sub-devices.
for device_desc in my_bridge.getDeviceDescriptionList():

    driver_desc = device_desc.getDriverDescription()
    
    # Again, we only keep devices controlled by the Inscoper Device Controller.
    if isinstance(driver_desc, inscoper_api.InscoperBoxDriverDescription):
        device_id = driver_desc.getHardwareId()
        
        # If this hardware_id matches one of the devices we found in our configuration...
        if device_id in device_map:
            current_device = device_map[device_id]
            sub_device_map = current_device.sub_device_map
            
            # Look at all possible sub-devices described for this hardware model.
            for sub_device_desc in device_desc.getSubDeviceDescriptionList():
                sub_device_tag = sub_device_desc.getTag()
                sub_device_type = sub_device_desc.getType() # The general purpose of the sub-device (e.g., CUBE, SHUTTER, etc.)
                
                # If this configured device actually uses this specific sub-device...
                if sub_device_tag in sub_device_map:
                    current_sub_device = sub_device_map[sub_device_tag]
                    
                    # Store the human-readable string of the sub-device type 
                    current_sub_device.inscoper_type = inscoper_api.Utils.subDeviceTypeToString(sub_device_type)

objective_turret_sub_device_id = None   # Turret that selects the objective
cube_turret_sub_device_id = None        # Filter-cube turret
tl_power_sub_device_id = None           # Power controller for the transmitted light
tl_shutter_sub_device_id = None         # Shutter inside the microscope for the transmitted light
epi_shutter_sub_device_id = None        # Shutter inside the microscope for the epi-fluorescence
led_blue_power_sub_device_id = None     # Power controller for the blue (440nm) LED
led_blue_shutter_sub_device_id = None   # Shutter inside the light source for the blue (440nm) LED

for device_id, device in device_map.items():
    for sub_device_tag, sub_device in device.sub_device_map.items():
        if sub_device.inscoper_type == "SHUTTER" and "TL" in sub_device.name:
            # Transmitted-light shutter: type is SHUTTER and the name contains "TL"
            tl_shutter_sub_device_id = inscoper_api.SubDeviceId(device.name, sub_device.name)
        elif sub_device.inscoper_type == "SHUTTER" and "IL" in sub_device.name and "Down" in sub_device.name:
            # Epi-fluorescence (incident-light) shutter: type is SHUTTER, path is "IL Down"
            epi_shutter_sub_device_id = inscoper_api.SubDeviceId(device.name, sub_device.name)
        elif sub_device.inscoper_type == "OBJECTIVE":
            # Objective turret: uniquely identified by the "OBJECTIVE" type
            objective_turret_sub_device_id = inscoper_api.SubDeviceId(device.name, sub_device.name)
        elif sub_device.inscoper_type == "CUBE" and "Down" in sub_device.name:
            # Filter-cube turret in the epi (downward) light path
            cube_turret_sub_device_id = inscoper_api.SubDeviceId(device.name, sub_device.name)
        elif ("Intensity" in sub_device.name or "Power" in sub_device.name) and "TL" in sub_device.name:
            # Transmitted-light intensity: name contains "Intensity" or "Power" AND "TL"
            tl_power_sub_device_id = inscoper_api.SubDeviceId(device.name, sub_device.name)
        elif ("Intensity" in sub_device.name or "Power" in sub_device.name) and "440" in sub_device.name:
            # 440 nm LED power: name contains "Intensity" or "Power" AND the wavelength "440"
            led_blue_power_sub_device_id = inscoper_api.SubDeviceId(device.name, sub_device.name)
        elif sub_device.inscoper_type == "SHUTTER" and "440" in sub_device.name:
            # 440 nm LED shutter: type is SHUTTER and the wavelength "440" appears in the name
            led_blue_shutter_sub_device_id = inscoper_api.SubDeviceId(device.name, sub_device.name)

blue_channel_description = {objective_turret_sub_device_id: 1,
             cube_turret_sub_device_id: 2,
             tl_power_sub_device_id: 0,
             tl_shutter_sub_device_id: 0,
             epi_shutter_sub_device_id: 1,
             led_blue_power_sub_device_id: 100,
             led_blue_shutter_sub_device_id: 1}

blue_status = inscoper_api.Status()
for sub_device_id, value in blue_channel_description.items():
    blue_status.addParam(sub_device_id, value)

# --8<-- [start:main_logic]

# ── Step 1: Resolve the sub-device IDs for the focus
focus_sub_device_id = None              # Focus controller
for device_id, device in device_map.items():
    for sub_device_tag, sub_device in device.sub_device_map.items():
        if sub_device.inscoper_type == "FOCUS":
            # Focus controller: uniquely identified by the "FOCUS" type
            focus_sub_device_id = inscoper_api.SubDeviceId(device.name, sub_device.name)


# ── Step 2: Start the camera in the correct mode
start_cam_status = inscoper_api.Status()
start_cam_status.addTag("MyCamera")
start_cam_status.addTag("SOFTWARE_TRIGGER")

my_bridge.loadSequence(0, "StartCamera", [start_cam_status])
my_bridge.runSequence(0, False)

# ── Step 3: Set the blue channel
my_bridge.loadSequence(1, "DeviceUpdate", [blue_status])
my_bridge.runSequence(1, False)


# ── Step 4: Wait for the user to adjust the focus on the microscope
input("Please manually adjust the focus on the microscope. Once done, press Enter to continue...")


# ── Step 5: Get current Z position and define the Zstack 
current_z = my_bridge.getLongValue(focus_sub_device_id)
print(f"Current Z position: {current_z} nm")

zstack_status = []
step = 10000  # 10 micron in nanometers (Inscoper Z focus unit)
volume = 100000  # 100 microns in nanometers
half_volume = volume // 2

for z in range(current_z - half_volume, current_z + half_volume + 1, step):
    slice_status = inscoper_api.Status()
    for sub_device_id, value in blue_channel_description.items():
        slice_status.addParam(sub_device_id, value)
    slice_status.addParam(focus_sub_device_id, z)
    slice_status.addTag("MyCamera")
    slice_status.addTag("SOFTWARE_TRIGGER")

    zstack_status.append(slice_status)

# ── Step 6: Load and run the acquisition
my_bridge.loadSequence(2, "Acquisition", zstack_status)
my_bridge.runSequence(2, False)

# ── Step 7: Retrieve and display the images
received_images = my_listener.getReceivedImages()

if received_images:
    N = len(received_images)
    cols = int(np.ceil(np.sqrt(N)))
    rows = int(np.ceil(N / cols))
    
    fig, axes = plt.subplots(rows, cols, figsize=(cols * 3, rows * 3))
    if N == 1:
        axes = np.array([axes])
    else:
        axes = axes.flatten()
        
    for idx, image in enumerate(received_images):
        image_data = image.getImageData()
        image_width = image.getWidth()
        image_height = image.getHeight()
        pixel_size_bytes = image.getPixelSize()
        bit_depth = image.getBitDepth()
        bytes_per_value = bit_depth // 8
        values_per_pixel = pixel_size_bytes // bytes_per_value
        img = np.reshape(image_data, (image_height, image_width, values_per_pixel))
        
        ax = axes[idx]
        ax.imshow(img[:, :, 0], cmap="gray")
        ax.set_title(f"Slice {idx}")
        ax.axis("off")
        
    # Hide any unused subplots in the grid
    for idx in range(N, len(axes)):
        axes[idx].axis("off")
        
    plt.tight_layout()
    plt.show()
else:
    print("No images received to plot.")

# --8<-- [end:main_logic]

my_bridge.close()
