class CustomTimeDialog(simpledialog.Dialog):
    def body(self, master):
        self.timebutton_style = {"font": ("consolas", 11), 
        "fg": "white", "bg": "#3c3c3c", "relief": "flat"}
        self.title('Custom Time')
        self.time_background = "#242424"
        self.time_fg="white"

        master.configure(bg=self.time_background)
        self.configure(bg=self.time_background)

        self.ico = self.resource_path_timer("icon.ico")
        self.iconbitmap(self.ico)

        #timebox--------------------------------------------------
        ctime_frame = tk.Frame(master, bg=self.time_background)
        ctime_frame.grid(row=1, column=1)
        self.timebox = tk.Listbox(ctime_frame, height=6, width=15, font=self.timebutton_style["font"], bg=self.timebutton_style["bg"], fg="#dddddd", selectbackground="#222222")

        for time_string in ['15s', '30s', '45s', '1m', '5m', '10m']:
            self.timebox.insert(tk.END, time_string)
        self.timebox.grid(row=1, column=1)
        self.timebox.bind('<<ListboxSelect>>', self.set_spinboxes_from_selection)

        #minutebox-----------------------------------------------
        # Main frame to contain the minutes and seconds frames
        time_frame = tk.Frame(ctime_frame, bg=self.time_background)
        time_frame.grid(row=2, column=1, pady=5)# side=tk.TOP, fill=tk.X, padx=5, pady=5)

        # Create a frame for the minutes spinbox and label
        minutes_frame = tk.Frame(time_frame, bg=self.time_background)
        minutes_frame.pack(side=tk.LEFT, fill=tk.X)#, padx=5)

        tk.Label(minutes_frame, text="Minutes:", bg=self.time_background, fg=self.time_fg, font=self.timebutton_style["font"]).pack(side=tk.TOP)
        self.spin_minutes = tk.Spinbox(minutes_frame, from_=0, to=59, width=5, font=self.timebutton_style["font"])
        self.spin_minutes.pack(side=tk.TOP)

        # Create a frame for the seconds spinbox and label
        seconds_frame = tk.Frame(time_frame, bg=self.time_background)
        seconds_frame.pack(side=tk.LEFT, fill=tk.X, padx=5)

        tk.Label(seconds_frame, text="Seconds:", bg=self.time_background, fg=self.time_fg, font=self.timebutton_style["font"]).pack(side=tk.TOP)
        self.spin_seconds = tk.Spinbox(seconds_frame, from_=0, to=59, value=15, width=5, font=self.timebutton_style["font"], wrap=True)
        self.spin_seconds.pack(side=tk.TOP)

        #togsessbox-------------------------------------------------
        session = tk.LabelFrame(master, fg=self.timebutton_style["fg"], bg=self.time_background, relief=tk.FLAT)#, text="Sessions"
        session.grid(row=1, column=2)

        #togsessbox = tk.Frame(master, bg=self.time_background)
        togsess_frame = tk.Frame(session, bg=self.time_background)
        togsess_frame.grid (row=3,column=1, pady=5)
        self.togsess_mode = tk.BooleanVar(value=False)

        #self.togsess_frame = tk.Checkbutton(togsess_frame, bg=self.time_background)
        self.togsess_checkbox = tk.Checkbutton(togsess_frame, text="Session", 
        variable=self.togsess_mode, command=self.toggle_togsess)
        self.togsess_checkbox.configure(**self.timebutton_style, bd=0)
        self.togsess_checkbox.grid(row=1, column=1, sticky=tk.E, ipadx=12)

        self.img_togsess = tk.Spinbox(togsess_frame, width=3, from_=0, to=100, 
        font=self.timebutton_style["font"], wrap=True, x=500, value=5, state = 'disabled')
        self.img_togsess.grid(row=1, column=2)

        #sessionsbox-----------------------------------------------------------
        self.sessionlist = ['5 pics for 30s', '5 pics for 1m', '5 pics for 5m']
        self.sessionString = tk.StringVar(value=self.sessionlist)
        self.sessionbox = tk.Listbox(session, height=6, width=18, font=self.timebutton_style["font"], bg=self.timebutton_style["bg"], listvariable=self.sessionString, borderwidth=0, state = 'disabled', fg="#dddddd", selectbackground="#222222")#, fg=self.timebutton_style["fg"])       

        self.sessionbox.grid(row=1, column=1)

        #session buttons frame------------------------------------------------------------------
        sessionbuttons = tk.Frame(session, bg=self.time_background)
        sessionbuttons.grid(row=2, column=1)
        self.add_button = tk.Button(sessionbuttons, text="+", width=3, command=self.add_session, default=tk.ACTIVE, state="disabled")
        self.add_button.config(**self.timebutton_style)
        self.add_button.grid(row=1, column=1)
        self.del_button = tk.Button(sessionbuttons, text="-", width=3, command=self.remove_session, default=tk.ACTIVE, state="disabled")
        self.del_button.config(**self.timebutton_style)
        self.del_button.grid(row=1, column=2, padx=(0,10))
        self.up_button = tk.Button(sessionbuttons, text="Ʌ", width=3, command=lambda: self.move(-1), default=tk.ACTIVE, state="disabled")
        self.up_button.config(**self.timebutton_style)
        self.up_button.grid(row=1, column=3)
        self.down_button = tk.Button(sessionbuttons, text="V", width=3, command=lambda: self.move(1), default=tk.ACTIVE, state="disabled")
        self.down_button.config(**self.timebutton_style)
        self.down_button.grid(row=1, column=4)
        return self.spin_seconds  # initial focus

    def add_session(self):
        try:
            img_togsess_value = int(self.img_togsess.get() or 0)
        except ValueError:
            img_togsess_value = 0

        try:
            minutes_input = int(self.spin_minutes.get() or 0)
        except ValueError:
            minutes_input = 0

        try:
            seconds_input = int(self.spin_seconds.get() or 0)
        except ValueError:
            seconds_input = 0

        # Convert total seconds to minutes and seconds
        minutes, seconds = divmod(minutes_input * 60 + seconds_input, 60)

        # Format the session string based on the minutes and seconds
        if minutes > 0 and seconds == 0:
            session_str = f"{img_togsess_value} pics for {minutes}m"
        elif minutes == 0 and seconds > 0:
            session_str = f"{img_togsess_value} pics for {seconds}s"
        elif minutes > 0 and seconds > 0:
            session_str = f"{img_togsess_value} pics for {minutes}m {seconds}s"
        else:
            # If both minutes and seconds are missing or 0, use 0s in the string
            session_str = f"{img_togsess_value} pics for 0s"

        # Append session string to the session list
        self.sessionlist.append(session_str)

        # Update the session string representation
        self.sessionString.set(self.sessionlist)

        # Select the newly added session in the session box
        self.sessionbox.selection_set(len(self.sessionlist) - 1)


    def remove_session(self):
        selected_index = self.sessionbox.curselection()
        if not selected_index:
            return

        selected_index = selected_index[0]
        self.sessionlist.pop(selected_index)
        self.sessionString.set(self.sessionlist)

        if selected_index < len(self.sessionlist):
            self.sessionbox.selection_set(selected_index)
        elif len(self.sessionlist) > 0:
            self.sessionbox.selection_set(len(self.sessionlist) - 1)

    def move(self, num):
        #num is -1 for up and 1 for down
        self.idxs = self.sessionbox.curselection()
        if not self.idxs:
            return
        for pos in self.idxs:
            text=self.sessionbox.get(pos) #gets text
            self.sessionbox.delete(pos) #removes text from list box
            self.sessionlist.pop(pos)  #removes text from list
            if pos==len(self.sessionlist) and num==1: pos=-1; #sets at beginning if at bottom and going down
            if pos==0 and num==-1: pos=len(self.sessionlist)+1; #sets at end if at top and going up
            self.sessionbox.insert(pos+num, text) #inserts into list box
            self.sessionlist.insert(pos+num, text) #inserts into list
            self.sessionbox.selection_set(pos+num)

    def toggle_togsess(self):
        if self.togsess_mode.get():
            self.togsess_checkbox.configure(fg="#2c2c2c", bg="#b8b8b8")
            self.img_togsess.config(state = 'normal')
            self.sessionbox.config (state = 'normal')
            self.add_button.config (state = 'normal')
            self.del_button.config (state = 'normal')
            self.up_button.config  (state = 'normal')
            self.down_button.config(state = 'normal')
        else:
            self.togsess_checkbox.configure(**self.timebutton_style)
            self.img_togsess.config(state = 'disabled')
            self.sessionbox.config (state = 'disabled')
            self.add_button.config (state = 'disabled')
            self.del_button.config (state = 'disabled')
            self.up_button.config  (state = 'disabled')
            self.down_button.config(state = 'disabled')
            

    def set_spinboxes_from_selection(self, event=None):
        index = self.timebox.curselection()
        if not index:
            return
        time_string = self.timebox.get(index)
        if 'm' in time_string:
            minutes = int(time_string.replace('m', ''))
            seconds = 0
        elif 's' in time_string:
            minutes = 0
            seconds = int(time_string.replace('s', ''))
        else:
            # Handle a possible unknown format
            self.bell()  # ring the bell to signal an error
            return

        self.spin_minutes.delete(0, tk.END)
        self.spin_minutes.insert(0, minutes)
        self.spin_seconds.delete(0, tk.END)
        self.spin_seconds.insert(0, seconds)
        
    def buttonbox(self):
        box = tk.Frame(self, bg=self.time_background)
        self.ok_button = tk.Button(box, text="Apply", width=16, command=self.ok, default=tk.ACTIVE)
        self.ok_button.config(**self.timebutton_style)
        self.ok_button.pack(side=tk.TOP, ipadx=5, pady=5)
        box.pack()

    def apply(self):
        minutes = int(self.spin_minutes.get())
        seconds = int(self.spin_seconds.get())
        self.result = minutes * 60 + seconds

    def validate(self):
        try:
            minutes = int(self.spin_minutes.get())
            seconds = int(self.spin_seconds.get())
            return True
        except ValueError:
            self.bell()
            return False

class ImageViewer:
    def __init__(self, root):
		#init methods codes
	def select_folder(self):
		#select folder
	def pause_timer(self):
    def set_timer_interval(self):
        self.root.attributes("-topmost", False)
        
        dialog = CustomTimeDialog(self.root)
        interval = dialog.result
        if interval:
            if interval < 1:  # Check if interval is less than 1 second
                interval = 1
            self.timer_interval = interval * 1000  # Convert to milliseconds
            self.set_timer_interval = self.timer_interval  # Store the set timer interval
        self.root.lift()  # Bring the main window to the top
        self.root.focus_force()  # Give focus to the main window
        
        minutes = self.timer_interval // 60000
        seconds = (self.timer_interval % 60000) // 1000
        
        if self.timer_interval <=59000:
            self.timer_label.config(text=f"{seconds}")
        else :
            self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")

        self.root.attributes("-topmost", True)
    def update_timer(self):
        # Calculate minutes and seconds left
        minutes = self.timer_interval // 60000
        seconds = (self.timer_interval % 60000) // 1000

        if self.timer_interval <=59000:
            self.timer_label.config(text=f"{seconds}")
        else :
            self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")
        
        if self.vol:
            if self.timer_interval == 3000:
                wave_obj = sa.WaveObject.from_wave_file(self.beep1)
                play_obj = wave_obj.play()
                play_obj.wait_done()
            if self.timer_interval == 2000:
                wave_obj = sa.WaveObject.from_wave_file(self.beep1)
                play_obj = wave_obj.play()
                play_obj.wait_done()
            if self.timer_interval == 1000:
                wave_obj = sa.WaveObject.from_wave_file(self.beep1)
                play_obj = wave_obj.play()
                play_obj.wait_done()
            if self.timer_interval == 0:
                wave_obj = sa.WaveObject.from_wave_file(self.beep2)
                play_obj = wave_obj.play()
                play_obj.wait_done()

        self.timer_interval -= 1000
            
        if self.timer_interval < 0:
            self.timer_interval = self.set_timer_interval  # Use the stored set timer interval
            self.next_image()
    def next_image(self, event=None):
        if self.image_folder != "":
            if len(self.image_files) == len(self.history):
                self.history_index = (self.history_index + 1) % len(self.image_files)
            else:
                self.add_image_to_history()
            self.display_image()
                # Reset the timer interval to the stored set timer interval
        self.timer_interval = self.set_timer_interval
    def previous_image(self, event=None):
        if self.image_folder != "":
            if self.history_index > 0:
                self.history_index -= 1
                self.display_image()
        self.timer_interval = self.set_timer_interval  # Use the stored set timer interval
		
class image viewer has a set_timer_interval tha calls the entire timer window.


the session box have 3 values, [order in the list, number of picture to be shown, and timer interval to be set]

i want it so that when self.togsess_mode is off or false, it uses the minute and seconds like it is but when it's on or true, and i press apply, the image viewer counts the image shown as the first image, and the timer is being set by the value in the sessionbox items instead of just the minutes and seconds spinbox.

so according to the example sessionlist, it sets the timer according to the first item for a few images (in the example its 5 images for 30s), then for the next number of images it follows the next item on the session list, setting the timer interval for a set of determined number of following images. then i can edit the session using the session box. when the session reaches it's end and it has shown the last item for the determined time, i want it to just run pause_timer method to pause the timer, and reset the image count to run the session again when i press start. give me the new methods with correct changes
























To accomplish your requirements, you will have to add some new functionality to the ImageViewer class, such as tracking the current image index, session index, and switching the session when the required number of images has been displayed for the set time interval. You'll also need to edit the CustomTimeDialog class to notify the ImageViewer about session changes when togsess_mode is enabled.

Let's break down the tasks to be done:

1. Add some attributes to your ImageViewer class to keep track of the session state.
2. Modify the CustomTimeDialog to communicate the sessions back to ImageViewer.
3. Adjust the ImageViewer class to handle sessions when togsess_mode is activated.
4. Reset the session when select_folder is called.
5. When the session reaches its end, pause the timer with pause_timer.

Here's a basic outline of how you might modify the ImageViewer class and integrate a custom session handler for the timing.

### ImageViewer modifications:

class ImageViewer:
    def init(self, root):
        # … existing init code …
        self.current_image_index = 0
        self.current_session_index = 0
        self.total_images_in_session = 0
        self.session_times = []
        self.images_displayed_in_current_session = 0

    def update_timer(self):
        # … original update timer code …

        if self.timer_interval < 0:
            if self.togsess_mode.get():  # If session mode is enabled
                self.images_displayed_in_current_session += 1
                if self.images_displayed_in_current_session >= self.total_images_in_session:
                    self.current_session_index += 1
                    self.images_displayed_in_current_session = 0
                    if self.current_session_index < len(self.session_times):
                        self.set_timer_interval = self.session_times[self.current_session_index] * 1000
                    else:
                        self.pause_timer()
                        return  # End of session list, timer paused

            self.next_image()  # Go to the next image
            self.timer_interval = self.set_timer_interval  # Reset the timer
        
    # … rest of the ImageViewer methods …

    def select_folder(self):
        # … existing code …
        # Reset the session
        self.current_session_index = 0
        self.current_image_index = 0
        self.images_displayed_in_current_session = 0
        
    def start_session_mode(self, session_times):
        # This method gets called when the dialog confirms session setup
        self.togsess_mode.set(True)
        self.session_times = session_times
        if len(session_times) > 0:
            self.set_timer_interval = session_times[0] * 1000
            self.total_images_in_session = ?  # This should set by the user via dialog
        
    def pause_timer(self):
        # … original pause timer code …


### CustomTimeDialog modifications:

For CustomTimeDialog, you need a way to pass the session information back. I'll demonstrate one way to do that.

class CustomTimeDialog(simpledialog.Dialog):
    # … existing CustomTimeDialog code …
    def apply(self):
        # … existing apply code …
        if self.togsess_mode.get():
            # You need to parse the session times from self.sessionlist here and convert them to seconds
            # For simplicity, let's assume a function called parse_session_times exists
            session_times = parse_session_times(self.sessionlist)
            self.result = session_times
        else:
            minutes = int(self.spin_minutes.get())
            seconds = int(self.spin_seconds.get())
            self.result = minutes * 60 + seconds


And then, in your ImageViewer's set_timer_interval method, you would call start_session_mode with the extracted session times from the dialog.

def set_timer_interval(self):
    # … existing code …
    if isinstance(dialog.result, list):
        self.start_session_mode(dialog.result)
    else:
        self.timer_interval = dialog.result * 1000


Remember that the new parse_session_times function should parse the string values from the self.sessionlist and return a list of integer times.

Finally, to ensure that the ImageViewer's pause method is called when the session completes, you will have reached the end of update_timer where if the current session index is past the session list, you could call the pause_timer method.

Please note that this solution is not complete and the parse_session_times function must be implemented. Moreover, you might need to do more adjustments, especially in handling user interface interactions and error checking.

This approach should give you a foundation to build the required session management into your application. You should unit-test each part of your code to ensure that all features are working correctly, especially the management of the timer according to sessions.