import tkinter as tk
from tkinter import ttk, messagebox
from PIL import Image, ImageTk
import os
import altmain
import video_processing
import cv2
import config_reader

class ImageDisplayApp:
    """
    @brief Main GUI application class for image processing and display
    
    @details This class provides a graphical interface for splitting images,
    processing videos, and displaying results with various blending options.
    """
    def __init__(self, root):
        """
        @brief Constructor for ImageDisplayApp class
        
        @param root Tkinter root window object
        """
        self.root = root
        self.root.title("Image Split & Update GUI")
        self.root.geometry("1000x750")
        self.root.configure(bg="#f5f5f5")
        self.cfg = config_reader.ConfigReader("config.ini")

        self.image_paths = {
            "main": self.cfg.get_image_path(),
            "left": "left.png",
            "right": "right.png"
        }

        self.image_frame = ttk.Frame(self.root, padding=10)
        self.image_frame.pack(pady=20)
        self.processor = altmain.ProjectionSplit()
        self.video_processor = video_processing.VideoProcessing("input.mp4")
        self.fps = 60
        self.is_running = True

        self.labels = {}
        for key in self.image_paths:
            lbl = ttk.Label(self.image_frame)
            lbl.pack(side=tk.LEFT, padx=10)
            self.labels[key] = lbl

        control_frame = ttk.Frame(self.root, padding=10)
        control_frame.pack(pady=10)

        ttk.Label(control_frame, text="Overlap (pixels):").grid(row=0, column=0, padx=5)
        self.param_var = tk.IntVar(value=self.cfg.get_overlap())
        entry = ttk.Entry(control_frame, textvariable=self.param_var, width=8)
        entry.grid(row=0, column=1, padx=5)

        ttk.Label(control_frame, text="Blend Type:").grid(row=0, column=2, padx=5)
        self.blend_var = tk.StringVar(value=self.cfg.get_blend_mode())
        blend_box = ttk.Combobox(
            control_frame,
            textvariable=self.blend_var,
            values=["linear", "quadratic", "gaussian"],
            state="readonly",
            width=12
        )
        blend_box.grid(row=0, column=3, padx=5)

        entry.bind("<FocusOut>", lambda e: self.debounced_update())
        blend_box.bind("<<ComboboxSelected>>", lambda e: self.debounced_update())

        timer_frame = ttk.Frame(self.root, padding=10)
        timer_frame.pack(pady=5)

        ttk.Label(timer_frame, text="Start Time (HH:MM:SS):").pack(side=tk.LEFT, padx=5)
        self.start_time_var = tk.StringVar(value="14:30:00")  # default example
        ttk.Entry(timer_frame, textvariable=self.start_time_var, width=10).pack(side=tk.LEFT, padx=5)

        ttk.Button(
            timer_frame,
            text="Start at Time",
            command=self.schedule_start
        ).pack(side=tk.LEFT, padx=10)


        fullscreen_frame = ttk.Frame(self.root, padding=10)
        fullscreen_frame.pack(pady=5)

        ttk.Button(
            fullscreen_frame,
            text="Show Left Fullscreen",
            command=lambda: self.show_fullscreen("left")
        ).pack(side=tk.LEFT, padx=10)

        ttk.Button(
            fullscreen_frame,
            text="Show Right Fullscreen",
            command=lambda: self.show_fullscreen("right")
        ).pack(side=tk.LEFT, padx=10)
        ttk.Button(
            fullscreen_frame,
            text="Run Video",
            command=self.run_video
        ).pack(side=tk.LEFT, padx=10)

        self._update_after_id = None

    def debounced_update(self):
        """
        @brief Debounced update to prevent rapid consecutive calls
        
        @details Cancels pending updates and schedules a new one after delay
        to prevent multiple rapid updates when parameters change.
        """
        if self._update_after_id is not None:
            self.root.after_cancel(self._update_after_id)
        self._update_after_id = self.root.after(500, self.run_and_update)

    def show_fullscreen(self, key):
        """
        @brief Display image in fullscreen mode
        
        @param key Image identifier ("left" or "right")
        @exception FileNotFoundError If image file does not exist
        """
        path = self.image_paths.get(key)
        if not os.path.exists(path):
            messagebox.showwarning("Missing Image", f"{path} not found.")
            return

        fullscreen = tk.Toplevel(self.root)
        fullscreen.attributes("-fullscreen", True)
        fullscreen.configure(bg="black")
        fullscreen.bind("<Escape>", lambda e: fullscreen.destroy())

        lbl = ttk.Label(fullscreen, background="black")
        lbl.pack(expand=True)

        def update_fullscreen():
            """
            @brief Update fullscreen display with current image
            
            @details Continuously updates the fullscreen display with
            the current image, resizing to fit screen while maintaining aspect ratio.
            """
            if not os.path.exists(path):
                return
            try:
                img = Image.open(path)
                screen_w = fullscreen.winfo_screenwidth()
                screen_h = fullscreen.winfo_screenheight()

                img_ratio = img.width / img.height
                screen_ratio = screen_w / screen_h

                if img_ratio > screen_ratio:
                    new_w = screen_w
                    new_h = int(screen_w / img_ratio)
                else:
                    new_h = screen_h
                    new_w = int(screen_h * img_ratio)

                img = img.resize((new_w, new_h), Image.LANCZOS)
                photo = ImageTk.PhotoImage(img)
                lbl.configure(image=photo)
                lbl.image = photo
            except Exception as e:
                print("Fullscreen update error:", e)

            fullscreen.after(100, update_fullscreen)

        update_fullscreen()

    def _update_image_widget(self, key, np_image):
        """
        @brief Update individual image widget with new image data
        
        @param key Widget identifier
        @param np_image Numpy array containing image data
        """
        if np_image is None:
            self.labels[key].configure(text=f"No image data", image="")
            self.labels[key].image = None
            return

        if np_image.shape[2] == 4:
            np_image = cv2.cvtColor(np_image, cv2.COLOR_BGRA2RGBA)
        else:
            np_image = cv2.cvtColor(np_image, cv2.COLOR_BGR2RGB)

        img = Image.fromarray(np_image)
        img = img.resize((300, 300))

        photo = ImageTk.PhotoImage(img)

        self.labels[key].configure(image=photo, text="")
        self.labels[key].image = photo

    def run_and_update(self):
        """
        @brief Process images and update display
        
        @details Applies current parameters to process images and
        updates all image displays with the results.
        
        @exception Exception Catches and displays any processing errors
        """
        try:
            overlap_value = int(self.param_var.get())
            blend_type = self.blend_var.get()
            self.processor.process_images(overlap_value, blend_type)
            self.update_images_from_arrays({"left": self.processor.image_left, "right": self.processor.image_right,
                                            "main": self.processor.image_main})
        except Exception as e:
            import traceback
            traceback.print_exc()
            print("TYPE OF E:", type(e))
            print("VALUE OF E:", repr(e))
            messagebox.showerror("Error", repr(e))
    def run_video(self):
        """
        @brief Process and display next video frame
        
        @details Retrieves next frame from video, processes it with
        current parameters, and updates the display.
        """

        if not self.is_running:
            return

        image = self.video_processor.get_next_frame()
        if image is None:
            print("End of video.")
            self.is_running = False
            return

        try:
            overlap_value = int(self.param_var.get())
            blend_type = self.blend_var.get()
            self.processor.process_frame(image, overlap_value, blend_type)
            self.update_images_from_arrays({
                "left": self.processor.image_left,
                "right": self.processor.image_right,
                "main": self.processor.image_main
            })
        except Exception as e:
            import traceback
            traceback.print_exc()
            messagebox.showerror("Error", repr(e))
            self.is_running = False
            return

        delay = int(1000 / self.fps)
        self.root.after(delay, self.run_video)

    def start_video(self):
        """
        @brief Start video processing and display
        """
        self.is_running = True
        self.run_video()

    def stop_video(self):
        """
        @brief Stop video processing and release resources
        """
        self.is_running = False
        if self.video_processor.cap is not None:
            self.video_processor.release()

    def update_images_from_arrays(self, images: dict):
        """
        @brief Update all image widgets from numpy arrays
        
        @param images Dictionary of image identifiers and numpy arrays
        """
        for key, np_img in images.items():
            self._update_image_widget(key, np_img)

    def schedule_start(self):
        """
        @brief Schedule video to start at specified time
        
        @details Parses time string and starts checking loop to begin
        video playback at the specified time.
        """

        import datetime
        target_str = self.start_time_var.get().strip()
        try:
            target_time = datetime.datetime.strptime(target_str, "%H:%M:%S").time()
            print(f"[Timer] Scheduled video start at {target_time}.")
            self._check_time_loop(target_time)
        except ValueError:
            print("[Timer] Invalid time format. Please use HH:MM:SS (e.g., 14:30:00).")

    def _check_time_loop(self, target_time):
        """
        @brief Internal method to check if target time has been reached
        
        @param target_time Target time to start video
        """

        import datetime
        now = datetime.datetime.now().time()

        if now >= target_time:
            print("[Timer] Target time reached — starting video.")
            self.start_video()
            return

        self.root.after(1000, lambda: self._check_time_loop(target_time))




if __name__ == "__main__":
    """
    @brief Main entry point for the application
    
    @details Creates Tkinter root window and starts the GUI application
    """
    root = tk.Tk()
    app = ImageDisplayApp(root)
    root.mainloop()