import panel as pn
import webview
import threading
import time

# Panel extension은 import 전에 호출
pn.extension('tabulator', sizing_mode="stretch_width", notifications=True)

from main_ui import HDF5ViewerUI

def start_panel_server(app):
    pn.serve(app, port=5006, show=False, start=True, verbose=False)

def get_screen_size():
    """화면 해상도 감지"""
    try:
        import tkinter as tk
        root = tk.Tk()
        root.withdraw()  # 창 숨기기
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        root.destroy()
        return screen_width, screen_height
    except:
        # tkinter를 사용할 수 없는 경우 기본값 반환
        return 1920, 1080

def main():
    viewer = HDF5ViewerUI()
    app = viewer.create_layout()
    
    server_thread = threading.Thread(target=start_panel_server, args=(app,), daemon=True)
    server_thread.start()
    time.sleep(2)
    
    # 화면 해상도 감지
    screen_width, screen_height = get_screen_size()
    
    # 화면의 85% 크기로 창 설정
    # window_width = int(screen_width * 0.85)
    window_height = int(screen_height * 0.85)
    
    # 최소 크기 설정 (화면 크기의 50%)
    min_width = int(screen_width * 0.5)
    min_height = int(screen_height * 0.5)
    
    window = webview.create_window(
        'LTIS',
        'http://localhost:5006',
        width=min_width,
        height=window_height,
        resizable=True,
        min_size=(min_width, min_height)
    )
    
    webview.start()

if __name__ == '__main__':
    main()