"""
Inscoper API Example Script: Snap Image (Status Sequence)
=========================================================
This script demonstrates how to snap images using a recipe-based Status sequence.

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 "singleCamera".
   Change it below if your configuration is named differently.
3. Device Names: Change target camera names (e.g., "MyCamera") to match your setup.
"""

# --8<-- [start:main_logic]

import os
import inscoper_api


# Macro to all Inscoper configurations
CONFIG_PATH = os.environ['InscoperConfigsPath']

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

# Initialize the bridge
my_bridge = inscoper_api.Bridge()
my_bridge.loadConfigFile(os.sep.join([CONFIG_PATH, "singleCamera"]))
my_bridge.initDevices()

# Instantiate and register our custom image listener
my_listener = CustomImageListener()
my_bridge.addImageListener(my_listener)

my_camera = my_bridge.getCamera("MyCamera")

# Create a sequence of actions using Status objects
# Instead of manually triggering the camera, we build a "Sequence"
# which can be executed sequentially
status_list = []
for i in range(0,5):
    # A Status represents the state of the system in an acquisition sequence
    status = inscoper_api.Status()
    
    # Calling the Snap recipe requires the name of the camera to be passed as a tag
    status.addTag("MyCamera")
    
    # Add this state to the status list.
    status_list.append(status)

# Create and load a sequence in the bridge
# - '0' is the sequence ID we are assigning it
# - '"Snap"' is the name of the recipe to be executed
# - 'status_list' contains the 5 individual states
my_bridge.loadSequence(0, "Snap", status_list)

# Run the sequence synchronously (the script will wait for the sequence to finish before continuing)
my_bridge.runSequence(0)

# Retrieve all received images from the listener after the sequence has finished running
received_images = my_listener.getReceivedImages()
print(f"Received {len(received_images)} images") # should be 5

my_bridge.close()

# --8<-- [end:main_logic]
