time for changing it all

This commit is contained in:
filipriec
2025-04-18 18:11:12 +02:00
parent bdcc10bd40
commit 09ccad2bd4
4 changed files with 125 additions and 55 deletions

View File

@@ -22,20 +22,26 @@ use crate::ui::handlers::context::DialogPurpose; // <-- Add DialogPurpose import
// Import SaveOutcome
use crate::tui::terminal::{EventReader, TerminalCore};
use crate::ui::handlers::render::render_ui;
use crate::tui::functions::common::login; // <-- Add login module import
use crate::tui::functions::common::login;
use crate::tui::functions::common::login::LoginResult;
use std::time::Instant;
use std::error::Error;
use crossterm::cursor::SetCursorStyle;
use crossterm::event as crossterm_event;
use tracing::{info, error};
use tokio::sync::mpsc;
pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
pub async fn run_ui() -> Result<(), Box<dyn Error + Send + Sync>> {
let config = Config::load()?;
let theme = Theme::from_str(&config.colors.theme);
let mut terminal = TerminalCore::new()?;
let mut grpc_client = GrpcClient::new().await?;
let mut command_handler = CommandHandler::new();
let mut event_handler = EventHandler::new().await?;
// --- Channel for Login Results ---
let (login_result_sender, mut login_result_receiver) =
mpsc::channel::<LoginResult>(1);
let mut event_handler = EventHandler::new(login_result_sender.clone()).await?;
let event_reader = EventReader::new();
let mut auth_state = AuthState::default();
@@ -136,47 +142,6 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
}
// --- End Cursor Visibility Logic ---
// --- 2. Check for Pending Login Action ---
if login_state.login_request_pending {
// Reset the flag *before* calling save
login_state.login_request_pending = false;
// Create AuthClient and call save
match AuthClient::new().await {
Ok(mut auth_client_instance) => {
// Call the ORIGINAL save function from the login module
let save_result = login::save(
&mut auth_state,
&mut login_state,
&mut auth_client_instance, // Pass the new client instance
&mut app_state,
).await;
// Use tracing for logging the outcome
match save_result {
// save returns Result<String, Error>, Ok contains the message
Ok(msg) => info!(message = %msg, "Login save result"), // Use tracing::info!
Err(e) => error!(error = %e, "Error during login save"), // Use tracing::error!
}
// Note: save already handles showing the final dialog (success/failure)
}
Err(e) => {
// Handle client connection error - show dialog directly
// Ensure flag is already false here
app_state.show_dialog( // Use show_dialog, not update_dialog_content
"Login Failed",
&format!("Connection Error: {}", e),
vec!["OK".to_string()],
DialogPurpose::LoginFailed, // Use appropriate purpose
);
login_state.error_message = Some(format!("Connection Error: {}", e));
error!(error = %e, "Failed to create AuthClient"); // Use tracing::error!
}
}
// After save runs, the state (dialog content, etc.) is updated.
// The *next* iteration's draw call will show the final result.
} // --- End Pending Login Check ---
let total_count = app_state.total_count;
let mut current_position = app_state.current_position;
let position_before_event = current_position;
@@ -211,6 +176,63 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
// This happens *after* the event is handled
app_state.current_position = current_position;
// --- Check for Login Results from Channel ---
match login_result_receiver.try_recv() {
Ok(login_result) => {
// A result arrived from the login task!
match login_result {
LoginResult::Success(response) => {
// Update AuthState
auth_state.auth_token = Some(response.access_token.clone());
auth_state.user_id = Some(response.user_id.clone());
auth_state.role = Some(response.role.clone());
auth_state.decoded_username = Some(response.username.clone());
// Update Dialog
let success_message = format!(
"Login Successful!\n\nUsername: {}\nUser ID: {}\nRole: {}",
response.username, response.user_id, response.role
);
// Use update_dialog_content if loading dialog is shown, otherwise show_dialog
app_state.update_dialog_content( // Assuming loading dialog was shown
&success_message,
vec!["Menu".to_string(), "Exit".to_string()],
DialogPurpose::LoginSuccess,
);
info!(message = %success_message, "Login successful");
}
LoginResult::Failure(err_msg) => {
app_state.update_dialog_content( // Update loading dialog
&err_msg,
vec!["OK".to_string()],
DialogPurpose::LoginFailed,
);
login_state.error_message = Some(err_msg.clone()); // Keep error message
error!(error = %err_msg, "Login failed");
}
LoginResult::ConnectionError(err_msg) => {
app_state.update_dialog_content( // Update loading dialog
&err_msg, // Show connection error
vec!["OK".to_string()],
DialogPurpose::LoginFailed,
);
login_state.error_message = Some(err_msg.clone());
error!(error = %err_msg, "Login connection error");
}
}
// Clear login form state regardless of outcome now that it's processed
login_state.username.clear();
login_state.password.clear();
login_state.set_has_unsaved_changes(false);
login_state.current_cursor_pos = 0;
}
Err(mpsc::error::TryRecvError::Empty) => { /* No message waiting */ }
Err(mpsc::error::TryRecvError::Disconnected) => {
error!("Login result channel disconnected unexpectedly.");
// Optionally show an error dialog here
}
}
// --- Centralized Consequence Handling ---
let mut should_exit = false;
match event_outcome_result {