class ImageViewer:
    def __init__(self, root):

    def set_timer_interval(self):
        #if self.root.attributes("-topmost", True):
        #    self.root.attributes("-topmost", False)
        
        if not hasattr(self, 'current_session_timings'):  # Make sure the properties exist
            self.current_session_timings = []
            self.is_session_mode = False

        dialog = CustomTimeDialog(self.root, self.current_session_timings, self.is_session_mode)
        if dialog.result is not None:
            self.is_session_mode = dialog.togsess_mode.get()  # Ensure you're accessing the toggled state from the dialog

            if self.is_session_mode:
                try:
                    self.current_session_timings = dialog.result
                    # Session mode is active, dialog.result contains the list of session strings
                    self.process_session(dialog.result)
                    # Set the interval to the first session's time
                    self.timer_interval = self.current_session_list[0][1] * 1000
                    self.session_image_count = self.current_session_list[0][0]
                except IndexError as e:
                    self.is_session_mode=False
                    
            else:
                # Session mode is inactive, dialog.result should be a numerical value 
                interval = dialog.result
                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
        else: 
            pass
        #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}")

    def process_session(self, session_list):
        self.current_session_list = []
        for session_str in session_list:
            try:
                num_pic, time_str = session_str.split(' pic for ')
                minutes, seconds = self.parse_time(time_str)
                self.current_session_list.append((int(num_pic), minutes * 60 + seconds))
            except ValueError as e:
                # Handle the error appropriately, e.g., by logging or messaging the user
                pass  # Or whatever error handling you choose
                
    def parse_time(self, time_str):
        splits = time_str.split('m')
        minutes = 0
        seconds = 0
        
        if len(splits) > 1:
            minutes = int(splits[0])
            # Check if there is actually a seconds part after splitting by 'm'
            seconds_part = splits[1].replace('s', '').strip()
            if seconds_part:  # If the seconds part is not empty, convert it to an integer
                seconds = int(seconds_part)
        else:
            seconds = int(splits[0].replace('s', '').strip())
            
        return minutes, seconds
        
    def pause_timer(self):
        if self.timer is not None:
            self.root.after_cancel(self.timer)
            self.timer = None
        if self.session_active:
            self.session_index = 0
            self.session_image_count = self.current_session_list[0][1]
            self.timer_interval = self.current_session_list[0][1] * 1000
            
    def start_timer(self):
        if self.session_completed:
            # If the session is completed and the timer is started again, reset the session
            self.session_completed = False
            self.session_index = 0
            self.session_image_count = self.current_session_list[0][0]
            self.timer_interval = self.current_session_list[0][1] * 1000
            #self.timer_label.config(text="Start again?")  # Update the label to indicate a new start
            #return
        if self.image_folder != "" and not self.is_paused:# and not self.session_completed:
            self.update_timer()
            if not self.session_completed:
                self.timer = self.root.after(1000, self.start_timer)
                
    def update_timer(self):
        #if self.session_completed:
        #    # If the session is completed, display "done" and don't update the timer further
        #    self.timer_label.config(text="doner")
        #    return
            
        # 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 display_image(self): 
        if self.image_folder != "" and len(self.image_files) > 0:
            if self.update_switch_timestamps():
                # Show the text of the image name instead of loading the actual image
                image_name =  self.history[self.history_index]
                self.canvas.delete("all")  # Clear the canvas
                self.canvas.create_text(
                    self.canvas.winfo_width() // 2, 
                    self.canvas.winfo_height() // 2,
                    text=image_name,
                    fill="white"
                )
                # Schedule the image load with a delay
                if self.timer is not None:
                    self.root.after_cancel(self.timer) # Cancel existing timer to avoid conflicts
                self.timer = self.root.after(500, self.load_image_delayed) # Set a new timer to load the image after 500ms

            else:
                # Load the image normally if not quick-switching
                self.current_image_index = self.history[self.history_index]
                image_path = os.path.join(self.image_folder, self.current_image_index)
                self.path_to_open = image_path
                threading.Thread(target=self.load_image, args=(image_path,)).start()
                
    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
       
        if self.is_session_mode and not self.session_completed:
            print (self.session_completed)
            print (self.session_image_count)
            self.session_image_count -= 1
            if self.session_image_count <= 0:
                # move to the next session item or end the session if it's the last step
                if self.session_index < len(self.current_session_list) - 1:
                    self.session_index += 1
                    self.session_image_count, interval = self.current_session_list[self.session_index]
                    self.timer_interval = interval * 1000
                else:
                    # End of the session, update the label and stop the timer
                    self.timer_label.config(text="done")
                    #self.pause_timer() # Stops the timer
                    if not self.is_paused:
                        #self.start_pause_slideshow()
                        self.pause_timer()
                        self.start_button.config(text="Start", **self.button_green)
                        self.timer_label.configure(bg="green")
                        self.is_paused = True  # Set paused flag to True

                    self.session_completed = True  # Set completion flag
                    #return  # Exit early to avoid resetting the timer below
            else:
                #show the next image
                _, interval = self.current_session_list[self.session_index]
                self.timer_interval = interval * 1000
                #self.timer_interval = self.current_session_list[0][1] * 1000
                print ("what")
        elif self.is_session_mode and self.session_completed:
            print ("bob")
            return
        else:
            # Reset the timer if session mode is not active or after the session is completed
            print ("huh")
            self.timer_interval = self.set_timer_interval
        
    def previous_image(self, event=None):
        if self.image_folder != "" and self.history_index > 0:
            self.history_index -= 1
            self.display_image()

        # When session is active, control the flow based on session settings
        if self.is_session_mode:
            current_count, _ = self.current_session_list[self.session_index]
            # Move to the previous session step, if it's the first image in the current session step
            if self.session_image_count == current_count:
                if self.session_index > 0:
                    self.session_index -= 1
                else:
                    self.session_index = len(self.current_session_list) - 1
                _, interval = self.current_session_list[self.session_index]
                self.session_image_count = self.current_session_list[self.session_index][0]
                self.timer_interval = interval * 1000
            else:
                self.session_image_count += 1
                _, interval = self.current_session_list[self.session_index]
                self.timer_interval = interval * 1000
        else:
            # For regular (non-session) mode, simply reset the timer interval
            self.timer_interval = self.set_timer_interval
            
class CustomTimeDialog(simpledialog.Dialog):
    
    last_set_minutes = 0
    last_set_seconds = 30  # Default 30 seconds if no last value set
    def __init__(self, parent, current_session_timings=None, is_session_mode=False, **kwargs):
        self.sessionlist = []
        # Only set defaults if current_session_timings is None or empty
        if not current_session_timings:  # This checks both None and empty list [] conditions
            # Set default initial list here (only if there are no existing session timings)
            current_session_timings = ['2 pics for 2s', '3 pics for 1m']
        self.current_session_timings = current_session_timings
        self.is_session_mode = is_session_mode
        super().__init__(parent, **kwargs)
    def body(self, master): 
        self.togsess_mode.set(self.is_session_mode)
        if self.is_session_mode:
            self.toggle_togsess()  # Initialize the state of session elements based on current setting

        # Update the Listbox content with the current session timings:
        self.sessionString.set(self.current_session_timings)
        self.sessionlist = list(self.current_session_timings)

        return self.spin_seconds  # initial focus
        
what if i want the imageviewer to show a label saying rest when the parsed text say "rest", for instance if i set the current_session_timings = ['2 pics for 2s', "rest for 5m", '3 pics for 1m']