1use crate::{utils::println, User};
2use std::{env, net};
3
4pub enum Command {
5 Connect(String),
6 Open,
7}
8
9pub enum InputError {
10 InvalidCmd(String),
11 NoCommand,
12}
13
14impl InputError {
15 pub fn to_string(&self) -> String {
16 match self {
17 InputError::InvalidCmd(msg) => msg.to_string(),
18 InputError::NoCommand => "No command given".to_string(),
19 }
20 }
21}
22
23pub fn parse_command(input: &mut env::Args) -> Result<Command, InputError> {
24 input.next();
25
26 match input.next().as_deref() {
27 Some("open") => Ok(Command::Open),
28 Some("connect") => {
29 let host = input.next().ok_or(InputError::InvalidCmd(
30 "connect requires IP address".to_string(),
31 ))?;
32
33 Ok(Command::Connect(host))
34 }
35
36 Some(cmd) => Err(InputError::InvalidCmd(format!("invalid command: {}", cmd))),
37 None => Err(InputError::NoCommand),
38 }
39}
40
41pub fn connect(addr: &str) {
42 let stream = net::TcpStream::connect(addr).expect("Failed to connect to server");
43 let user = User::new_get_name(stream);
44 user.start_session();
45}
46
47pub fn open() {
48 let url = format!("{}:{}", "0.0.0.0", 8080);
49 let socket = net::TcpListener::bind(url).unwrap();
50
51 println("Waiting for connection...");
52 let (stream, addr) = socket.accept().unwrap();
53
54 println(format!("Connected to {}", addr).as_str());
55 let user = User::new_get_name(stream);
56 user.start_session()
57}