use crate::command_utils::configure_system_command;

#[tauri::command]
pub async fn select_image_file(app: tauri::AppHandle) -> Result<String, String> {
    use tauri_plugin_dialog::{DialogExt};

    println!("Opening image file dialog...");

    let file_path = app.dialog()
        .file()
        .add_filter("Image files", &["jpg", "jpeg", "png", "bmp", "gif", "tiff", "webp"])
        .blocking_pick_file();

    match file_path {
        Some(path) => {
            let path_str = path.to_string();
            println!("Selected image file: {}", path_str);
            Ok(path_str)
        }
        None => {
            println!("No image file selected");
            Err("No image file selected".to_string())
        }
    }
}

#[tauri::command]
pub async fn select_folder(app: tauri::AppHandle) -> Result<String, String> {
    use tauri_plugin_dialog::{DialogExt};

    println!("Opening folder dialog...");

    let folder_path = app.dialog()
        .file()
        .blocking_pick_folder();

    match folder_path {
        Some(path) => {
            let path_str = path.to_string();
            println!("Selected folder: {}", path_str);
            Ok(path_str)
        }
        None => {
            println!("No folder selected");
            Err("No folder selected".to_string())
        }
    }
}

#[tauri::command]
pub async fn open_folder(folder_path: String) -> Result<String, String> {
    println!("Opening folder: {}", folder_path);
    
    #[cfg(target_os = "windows")]
    {
        use std::process::Command;
        let mut cmd = Command::new("explorer");
        cmd.arg(&folder_path);

        // Configure console window hiding
        configure_system_command(&mut cmd);

        let result = cmd.spawn();

        match result {
            Ok(_) => Ok(format!("Opened folder: {}", folder_path)),
            Err(e) => Err(format!("Failed to open folder: {}", e))
        }
    }
    
    #[cfg(target_os = "macos")]
    {
        use std::process::Command;
        let result = Command::new("open")
            .arg(&folder_path)
            .spawn();
        
        match result {
            Ok(_) => Ok(format!("Opened folder: {}", folder_path)),
            Err(e) => Err(format!("Failed to open folder: {}", e))
        }
    }
    
    #[cfg(target_os = "linux")]
    {
        use std::process::Command;
        let result = Command::new("xdg-open")
            .arg(&folder_path)
            .spawn();
        
        match result {
            Ok(_) => Ok(format!("Opened folder: {}", folder_path)),
            Err(e) => Err(format!("Failed to open folder: {}", e))
        }
    }
}
