61 lines
1.7 KiB
Rust
61 lines
1.7 KiB
Rust
use anyhow::Result;
|
|
use ratatui::{widgets::ListState, DefaultTerminal};
|
|
|
|
use crate::{lobby::Lobby, message::{Message, MessageKind}, player::Player, ui::{ui, CurrentScreen}};
|
|
|
|
#[derive(Debug, Default)]
|
|
pub struct Client {
|
|
pub addr: String,
|
|
pub client: reqwest::Client,
|
|
pub user: Option<String>,
|
|
pub user_name: String,
|
|
pub exit: bool,
|
|
pub popup: bool,
|
|
pub popup_title: String,
|
|
pub popup_content: String,
|
|
pub response: String,
|
|
pub lobby: Option<String>,
|
|
pub lobby_id: String,
|
|
}
|
|
|
|
impl Client {
|
|
pub async fn run(&mut self, terminal: &mut DefaultTerminal) -> anyhow::Result<()> {
|
|
self.addr = "http://127.0.0.1:8080".to_string();
|
|
self.client = reqwest::Client::new();
|
|
|
|
while !self.exit {
|
|
terminal.draw(|frame| ui(frame, self))?;
|
|
crate::ui::handle_events(self).await?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub fn exit(&mut self) {
|
|
self.exit = true;
|
|
}
|
|
|
|
pub async fn send(&mut self, message: Message, addr: &str, path: &str) -> anyhow::Result<()> {
|
|
let response = self.client
|
|
.post([&addr, path].concat())
|
|
.header("Content-Type", "application/json")
|
|
.body(message.encode()?)
|
|
.send().await;
|
|
|
|
if let Err(e) = &response {
|
|
self.response = e.to_string();
|
|
return Ok(())
|
|
} else {
|
|
let response: Message = response?.json().await?;
|
|
self.response = format!("{:?}", &response);
|
|
|
|
match response.message_kind {
|
|
MessageKind::CreatePlayer => self.user = Some(response.content),
|
|
MessageKind::CreateLobby => self.lobby = Some(response.content),
|
|
_ => ()
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
}
|