# -*- coding: utf-8 -*-
 
import os
import time
from pinpong.board import *
from pinpong.extension.unihiker import *
from unihiker import GUI
 
# Initialize the UniHiker and the GUI
Board().begin()
gui = GUI()
 
# Define the folder where the images are stored
photo_folder = "/root/photo/"
 
# Get the list of image files sorted by modification time
def get_sorted_image_files():
    """Get a list of image files sorted by modification time."""
    try:
        files = [f for f in os.listdir(photo_folder) if f.endswith(".jpg")]
        files.sort(key=lambda x: os.path.getmtime(os.path.join(photo_folder, x)))
        return files
    except Exception as e:
        print(f"Error reading photo folder: {e}")
        return []
 
# Display an image on the screen
def display_image(file_name):
    """Display the given image on the UniHiker screen."""
    image_path = os.path.join(photo_folder, file_name)
    try:
        gui.clear()  # Clear previous image
        gui.draw_image(x=120, y=160, w=420, h=320, image=image_path, origin='center')
        print(f"Displaying image: {file_name}")
    except Exception as e:
        print(f"Error displaying image: {e}")
 
# Display a message on the screen
def display_message(message):
    """Display a message on the UniHiker screen."""
    gui.clear()
    gui.draw_text(x=120, y=160, text=message, font_size=8, origin='center')
    time.sleep(2)  # Display the message for 2 seconds
 
# Make the buzzer beep on button press
def beep_buzzer():
    """Play a short beep sound using the built-in buzzer."""
    buzzer.pitch(250, 1)  # Play a short beep sound at 250 Hz for 100 milliseconds
 
# Main function to handle image navigation
def navigate_images():
    """Navigate through the images in the 'photo' folder."""
    image_files = get_sorted_image_files()
    if not image_files:
        print("No images found in the photo folder.")
        return
 
    current_index = 0
    display_image(image_files[current_index])
 
    while True:
        if button_a.is_pressed():  # Check for button A (next image)
            print("Button A pressed - Next image")
            beep_buzzer()  # Play beep sound
            current_index = (current_index + 1) % len(image_files)
            display_image(image_files[current_index])
            time.sleep(0.1)  # Shorter delay to make navigation feel more responsive
 
            if current_index == 0:  # Looping back to the start
                display_message("End of images. Starting over...")
 
        elif button_b.is_pressed():  # Check for button B (previous image)
            print("Button B pressed - Previous image")
            beep_buzzer()  # Play beep sound
            current_index = (current_index - 1) % len(image_files)
            display_image(image_files[current_index])
            time.sleep(0.1)  # Shorter delay for responsiveness
 
            if current_index == len(image_files) - 1:  # Looping back to the end
                display_message("End of images. Starting back...")
 
        time.sleep(0.1)  # Short delay to reduce CPU load but keep it responsive
 
# Start the image navigation
navigate_images()