use crate::commands::serial::{disconnect_active_session, SerialConnectionState};
use tauri::{AppHandle, Manager, State, WebviewWindow};

fn main_window(app: &AppHandle) -> Result<WebviewWindow, String> {
    app.get_webview_window("main")
        .ok_or_else(|| "Can't find main window".to_string())
}

#[tauri::command]
pub fn win_minimize(app: AppHandle) -> Result<(), String> {
    main_window(&app)?
        .minimize()
        .map_err(|error| error.to_string())
}

#[tauri::command]
pub fn win_toggle_maximize(app: AppHandle) -> Result<(), String> {
    let window = main_window(&app)?;
    let is_maximized = window.is_maximized().map_err(|error| error.to_string())?;

    if is_maximized {
        window.unmaximize().map_err(|error| error.to_string())
    } else {
        window.maximize().map_err(|error| error.to_string())
    }
}

#[tauri::command]
pub async fn win_close(app: AppHandle, state: State<'_, SerialConnectionState>) -> Result<(), String> {
    disconnect_active_session(state.inner())
        .await
        .map_err(|error| error.to_string())?;

    app.exit(0);
    Ok(())
}
