import os
import random
from tkinter import Tk, Button, Label, filedialog, messagebox, IntVar, Spinbox, Checkbutton

class ImageBrowser:
    def __init__(self, master):
        self.master = master
        self.master.title("Image Browser")
        self.img_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
        self.image_pool = []  
        self.image_history = []  
          # Additional variable to know if we added new random image in the history
        self.new_random_image_added = False
        self.current_index = -1  
        self.image_folder = ""
        self.limit_message_shown = False
        self.button_open = Button(master, text="Open Image Folder", command=self.open_image_folder)
        self.button_open.pack()

        self.button_previous = Button(master, text="Previous Image", command=self.previous_image)
        self.button_previous.pack(side='left')

        self.button_next = Button(master, text="Next Image", command=self.next_image)
        self.button_next.pack(side='right')

        self.limit_enabled = IntVar()
        self.limit_checkbutton = Checkbutton(master, text="Limit", variable=self.limit_enabled)
        self.limit_checkbutton.pack(side='left')

        self.limit_var = IntVar(value=1)
        self.limit_spinbox = Spinbox(master, from_=1, to=100, width=5, textvariable=self.limit_var)
        self.limit_spinbox.pack(side='left')

        self.label_img_name = Label(master, text="Image Name: -")
        self.label_img_name.pack()

    def open_image_folder(self):
        folder_path = filedialog.askdirectory()
        if folder_path:
            self.image_folder = folder_path
            self.image_pool = [
                os.path.join(self.image_folder, f)
                for f in os.listdir(self.image_folder)
                if os.path.splitext(f)[1].lower() in self.img_EXTENSIONS
            ]
            random.shuffle(self.image_pool)
            self.show_image(0)

    def next_image(self):
        if not self.image_pool:
            messagebox.showinfo("No Images", "Please open an image folder first.")
            return

        if self.limit_enabled.get() and len(self.image_history) % self.limit_var.get() == 0 and self.image_history and not self.new_random_image_added:
            self.label_img_name.config(text="End of limit")
            return

        # If we are within the history boundaries, proceed with the next image in the history
        if self.current_index < len(self.image_history) - 1 and not self.new_random_image_added:
            self.current_index += 1
        else:  # Add a new random image
            self.current_index = self.get_random_unseen_image_index()
            self.image_history.append(self.current_index)
            self.new_random_image_added = True

        self.show_image(self.current_index)

    def previous_image(self):
        if not self.image_pool:
            messagebox.showinfo("No Images", "Please open an image folder first.")
            return

        if self.image_history and self.current_index > 0:
            # Go back in history without adding new random images
            self.current_index -= 1
            self.new_random_image_added = False
            self.show_image(self.current_index)
        elif self.image_history:
            # Add a new random image that hasn't been shown to the history
            new_image_index = self.get_random_unseen_image_index()
            self.image_history.insert(0, new_image_index)
            self.current_index = 0  # The new image is now the current
            self.show_image(self.current_index)
        else:
            messagebox.showinfo("No History", "No images in previous history.")
            
    def get_random_unseen_image_index(self):
        available_indices = set(range(len(self.image_pool))) - set(self.image_history)
        if available_indices:
            return random.choice(list(available_indices))
        else:
            # If all images have been seen, reshuffle the pool
            self.image_history = []
            random.shuffle(self.image_pool)
            return 0  # Begin from the start of the pool

    def show_image(self, index):
        img_name = os.path.basename(self.image_pool[index])
        self.label_img_name.config(text=f"Image Name: {img_name}")
        # Logic to display the image goes here (not shown in this snippet)

if __name__ == "__main__":
    root = Tk()
    image_browser = ImageBrowser(root)
    root.mainloop()
    
    "new"

why the next and previous seems disconnected. make the next image call from the history unless it's reached the end,  then add new random image that hasn't been called. and the previous call the previously shown images unless it reaches the beginning (top of the img history) then add a new random image that hasn't been called at the top of the history, so that if i press next i go through the history first then get a new random image. and if i press previous i can see  all previously called images, and when everytime reach the top of the history of shown images it adds a new random image that hasn't been called at the top of the history