import time
import logging
from PIL import Image, ImageSequence
from lib import LCD_1inch69  # Ensure this points to your correct LCD module library

# Set up logging
logging.basicConfig(level=logging.DEBUG)
RST = 27
DC = 25
BL = 18
bus = 0 
device = 0


class GifPlayer:
    def __init__(self):
        self.disp = LCD_1inch69.LCD_1inch69()
        self.disp.Init()
        self.disp.clear()  # Clear the screen
        self.disp.bl_DutyCycle(50)  # Set the backlight to 50%

    def play_gif_loop(self, gif_path, duration=3, delay=0.1):
        """Play a GIF for a specified duration on the screen."""
        try:
            # Open the gif image
            gif_image = Image.open(gif_path)

            # Logging the GIF information
            logging.info(f"GIF loaded: {gif_path}")
            total_frames = gif_image.n_frames
            logging.info(f"Total frames in GIF: {total_frames}")

            start_time = time.time()
            
            while time.time() - start_time < duration:
                for frame in range(total_frames):
                    if time.time() - start_time >= duration:
                        break  # Exit the loop once the specified duration is over

                    # Get the current frame
                    gif_image.seek(frame)
                    frame_image = gif_image.convert("RGB")  # Convert to RGB if needed
                    #resized_frame = frame_image.resize((self.disp.width, self.disp.height))  # Resize to fit the display
                    rotated = frame_image.rotate(90, expand=False)  # Rotate image by 180 degrees
                    resized = rotated.resize((self.disp.width, self.disp.height))  # Resize image to fit the display
                    self.disp.ShowImage(resized)
                    # Display the resized frame on the LCD
                    #self.disp.ShowImage(resized_frame)
                    logging.info(f"Displaying frame {frame + 1} of {total_frames}")
                    time.sleep(delay)  # Wait before displaying the next frame

        except KeyboardInterrupt:
            print("[INFO] Stopped by user")
        except Exception as e:
            logging.error(f"[ERROR] {e}")
        #finally:
            # Once the GIF is done, display a black screen
           # self.black_screen()

    def display_image(self, image_path):
        """Display a single image on the screen."""
        try:
            
            frame_image = Image.open(image_path)  # Load image properly
            resized_frame = frame_image.rotate(90).resize((self.disp.width, self.disp.height))
            #frame_image.resize((self.disp.width, self.disp.height)).rotate(180)
            self.disp.ShowImage(resized_frame)
            logging.info(f"Displaying image: {image_path}")
        except Exception as e:
            logging.error(f"[ERROR] Failed to load image: {e}")

    def black_screen(self):
        """Display a black screen."""
        try:
            blank = Image.new("RGB", (self.disp.width, self.disp.height), "black")
            self.disp.ShowImage(blank)
            time.sleep(2)  # Show black screen for 2 seconds
        except Exception as e:
            logging.error(f"[ERROR] Failed to display black screen: {e}")
