class ImageViewer:
    def __init__(self, root):
        #init codes
    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:
                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]
                 
            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_pics, time_str = session_str.split(' pics for ')
                minutes, seconds = self.parse_time(time_str)
                self.current_session_list.append((int(num_pics), 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')
        if len(splits) > 1:
            minutes = int(splits[0])
            seconds = int(splits[1].replace('s', ''))
        else:
            minutes = 0
            seconds = int(time_str.replace('s', ''))
        return minutes, seconds
    
    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}")

        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 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.image_folder != "" and not self.is_paused:
            self.update_timer()
            self.timer = self.root.after(1000, self.start_timer)


    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
       
        if self.is_session_mode:
            print (f"{self.session_image_count} initial ")
            self.session_image_count -= 1
            if self.session_image_count <= 0:
                self.session_index = (self.session_index + 1) % len(self.current_session_list)
                self.session_image_count, interval = self.current_session_list[self.session_index]
                self.timer_interval = interval * 1000  # Setting the new interval from session
                self.set_timer_interval = interval * 1000
                print ("here")
                print (f"{self.session_image_count} last ")
            else:
                print ("WHAT")

                self.timer_interval = self.current_session_list[0][1] * 1000

        else:
            self.timer_interval = self.set_timer_interval

            print ("what")
        
    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):
    def __init__(self, parent, current_session_timings=None, is_session_mode=False, **kwargs):
        # 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 = ['3 pics for 2s', '1 pics for 1s', '1 pics for 3s']
        self.current_session_timings = current_session_timings
        self.is_session_mode = is_session_mode
        super().__init__(parent, **kwargs)
    def body(self, master):
                #sessionsbox-----------------------------------------------------------
        self.sessionlist = []
        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)
        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)


    def apply(self):
        if self.togsess_mode.get():
            # In session mode, store the list of session strings directly
            self.result = self.sessionlist  # Use the list directly instead of self.sessionString.get()
        else:
            # In standard mode, parse and combine minutes and seconds to a single interval in seconds
            try:
                minutes = int(self.spin_minutes.get())
                seconds = int(self.spin_seconds.get())
                self.result = minutes * 60 + seconds  # Total time in seconds
            except ValueError:
                # Fall back to a default interval as needed
                self.result = 1  # Default to 1 second

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

i want the timer to pause and stop after it goes through the list once, update the timer with a text that says "done" then if i press next or play, it just continues and begin with the session again. i just want there to be a break after going through the sessionlist