# radar_data_reader/gui/gui_utils.py

"""
GUI utility functions, such as window centering logic, that can be reused
across different parts of the application or other projects.
"""

import tkinter as tk
from typing import Optional


def center_window(
    window: tk.Tk | tk.Toplevel, parent: Optional[tk.Tk | tk.Toplevel] = None
):
    """
    Centers a Tkinter window on the screen or relative to a parent window.

    This function should be called after the window's initial size has been
    set or determined, typically after creating all its widgets. Using
    `window.update_idletasks()` right before this call ensures that the
    window's dimensions are up-to-date.

    Args:
        window: The Tkinter window (tk.Tk or tk.Toplevel) to be centered.
        parent: The optional parent window. If provided, `window` will be
                centered relative to the parent. If None, `window` will be
                centered on the screen.
    """
    window.update_idletasks()  # Ensure window dimensions are calculated

    # Get window's dimensions
    win_width = window.winfo_width()
    win_height = window.winfo_height()

    if parent:
        # Center relative to the parent window
        parent.update_idletasks()
        parent_x = parent.winfo_x()
        parent_y = parent.winfo_y()
        parent_width = parent.winfo_width()
        parent_height = parent.winfo_height()

        pos_x = parent_x + (parent_width // 2) - (win_width // 2)
        pos_y = parent_y + (parent_height // 2) - (win_height // 2)
    else:
        # Center on the screen
        screen_width = window.winfo_screenwidth()
        screen_height = window.winfo_screenheight()

        pos_x = (screen_width // 2) - (win_width // 2)
        pos_y = (screen_height // 2) - (win_height // 2)

    # Set the window's position
    window.geometry(f"{win_width}x{win_height}+{pos_x}+{pos_y}")
    window.deiconify()  # Ensure window is visible
