use std::sync::{Arc, RwLock};
use tokio::sync::Mutex;
use crate::config::{DisplayConfig, OutputFormat};
use crate::repl::CursorState;
#[derive(Debug, Clone)]
pub struct SharedState {
pub current_database: Arc<RwLock<String>>,
pub connected: Arc<RwLock<bool>>,
pub server_version: Arc<RwLock<Option<String>>>,
pub output_format: Arc<RwLock<OutputFormat>>,
pub color_enabled: Arc<RwLock<bool>>,
cursor_state: Arc<Mutex<Option<CursorState>>>,
}
impl SharedState {
pub fn new(database: String) -> Self {
Self::with_config(database, &DisplayConfig::default())
}
pub fn with_config(database: String, display_config: &DisplayConfig) -> Self {
Self {
current_database: Arc::new(RwLock::new(database)),
connected: Arc::new(RwLock::new(false)),
server_version: Arc::new(RwLock::new(None)),
output_format: Arc::new(RwLock::new(display_config.format)),
color_enabled: Arc::new(RwLock::new(display_config.color_output)),
cursor_state: Arc::new(Mutex::new(None)),
}
}
pub async fn set_cursor(&self, state: CursorState) {
let mut cursor = self.cursor_state.lock().await;
*cursor = Some(state);
}
pub async fn get_cursor_mut(&self) -> tokio::sync::MutexGuard<'_, Option<CursorState>> {
self.cursor_state.lock().await
}
pub async fn clear_cursor(&self) {
let mut cursor = self.cursor_state.lock().await;
*cursor = None;
}
#[allow(dead_code)]
pub async fn has_cursor(&self) -> bool {
let cursor = self.cursor_state.lock().await;
cursor.is_some()
}
pub fn get_database(&self) -> String {
self.current_database.read().unwrap().clone()
}
pub fn set_database(&mut self, database: String) {
*self.current_database.write().unwrap() = database;
}
pub fn get_format(&self) -> OutputFormat {
*self.output_format.read().unwrap()
}
pub fn set_format(&self, format: OutputFormat) {
*self.output_format.write().unwrap() = format;
}
pub fn get_color_enabled(&self) -> bool {
*self.color_enabled.read().unwrap()
}
pub fn set_color_enabled(&self, enabled: bool) {
*self.color_enabled.write().unwrap() = enabled;
}
pub fn is_connected(&self) -> bool {
*self.connected.read().unwrap()
}
pub fn set_connected(&mut self, version: Option<String>) {
*self.connected.write().unwrap() = true;
*self.server_version.write().unwrap() = version;
}
}