	# -*- coding: utf-8 -*-
from pinpong.board import *
from pinpong.extension.unihiker import *
from unihiker import GUI  # Import GUI from the unihiker module
import cv2
import requests
import numpy as np
from datetime import datetime
import time
import os  # Import os module to handle directory operations
 
# Initialize the UniHiker and the screen GUI
Board().begin()
gui = GUI()  # Create a GUI object to handle the display
 
# Use the correct capture URL from your ESP32 camera
stream_url = "http://192.168.122.70/capture"  # Update with your ESP32 IP address
 
# Directory to save captured images
photo_directory = "/root/photo"
 
# Create the photo directory if it doesn't exist
if not os.path.exists(photo_directory):
    os.makedirs(photo_directory)
    print(f"Created directory: {photo_directory}")
 
last_button_b_press = 0  # To handle debounce
debounce_time = 0.3  # 300 milliseconds debounce time
 
def capture_and_display_image():
    """Capture an image from the ESP32 camera, display it on the UniHiker screen, and save it."""
    try:
        response = requests.get(stream_url, timeout=5)  # Set a timeout for the request
        if response.status_code == 200:
            img_array = np.array(bytearray(response.content), dtype=np.uint8)
            frame = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
 
            if frame is not None:
                # Rotate the frame 90 degrees counterclockwise
                frame = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)
 
                # Create a unique filename using a timestamp
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                file_name = os.path.join(photo_directory, f"captured_image_{timestamp}.jpg")  # Save in the photo directory
 
                # Save the rotated image in the UniHiker photo folder
                success = cv2.imwrite(file_name, frame)  # Attempt to save the image
 
                if success:
                    print(f"Image captured, rotated, and saved as '{file_name}'")
                else:
                    print(f"Failed to save the image as '{file_name}'")
 
                # Clear the screen and display the saved image on the UniHiker screen
                gui.clear()  # Clear previous drawings
                time.sleep(0.05)
 
                gui.draw_image(x=120, y=160, w=420, h=320, image=file_name, origin='center', onclick=lambda: print("Image clicked"))
 
                # Add a delay to allow the image to be displayed before the next capture
                time.sleep(1.5)  # 1.5 seconds delay for better visibility
 
            else:
                print("Failed to decode image")
        else:
            print(f"Failed to connect to the camera stream. Status code: {response.status_code}")
    except requests.exceptions.Timeout:
        print("Request timed out. Please check the ESP32 connection.")
    except Exception as e:
        print(f"An error occurred: {e}")
 
def delete_all_images():
    """Delete all images in the photo directory."""
    try:
        for filename in os.listdir(photo_directory):
            file_path = os.path.join(photo_directory, filename)
            if os.path.isfile(file_path):
                os.remove(file_path)  # Remove the file
                print(f"Deleted image: {file_path}")
        print("All images deleted successfully.")
    except Exception as e:
        print(f"An error occurred while deleting images: {e}")
 
while True:
    current_time = time.time()
 
    # Check if button A is pressed (for deleting images)
    if button_a.is_pressed():
        print("Button A is pressed. Deleting all images...")
        delete_all_images()  # Call the function to delete images
 
    # Check if button B is pressed, with debounce handling
    if button_b.is_pressed():
        print("Button B is pressed.")  # Debug print
        if current_time - last_button_b_press > debounce_time:
            last_button_b_press = current_time  # Update last press time
            print("Button B pressed. Capturing, rotating, and displaying image...")
            capture_and_display_image()  # Capture and display the image
 
    # Sleep for a short time to avoid overloading CPU
    time.sleep(0.1)  # 100 milliseconds pause to reduce CPU load