1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use binary_utils::{DataWriter, Result, write_bytes, DataReader, Error, consume_utf16be_char, PacketReader};
use datatypes::{VarInt, UnsignedShort, Enum, String};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite};

use crate::datatypes::datatype_definition::important_enums::HandshakeNextState;

/// Struct for the legacy ping response
pub struct LegacyPongPacket {
    server_version: std::string::String,
    motd: std::string::String,
    current_players: u16,
    max_players: u16
}
/// Struct for the `Handshake` packet used to tell the server in which state he should switch for
/// the following packets
pub struct HandshakePacket {
    /// annotation of the protocol version that the client uses to let the server decide if he is
    /// capable of comunicating with the client or not
    pub protocol: VarInt,
    /// Address used to connect to the server, can be used to check if the client connected how it
    /// should has
    pub address: String,
    /// Port that the client used to connect to the server
    pub port: UnsignedShort,
    /// enum to tell the server in which state he should switch after this packet
    pub next_state: Enum<HandshakeNextState, VarInt>
}
/// Struct to be able to read a legacy ping packet of a datastream
pub struct LegacyPingPacket;
impl LegacyPongPacket {
    /// function to initialize a new instance of `LegacyPingPacket`
    ///
    /// # Arguments
    ///
    /// `server_version` - A String containing the version of the server
    /// `motd` - A String of the motd
    /// `current_players` - An u16 representing, how much players are currently connected to the
    /// server
    /// `max_players` - An u16 representing, how much players are allowed to join the server
    pub fn new(server_version: std::string::String, motd: std::string::String, current_players: u16, max_players: u16) -> Self {
        Self{ server_version, motd, current_players, max_players }
    }
}
impl DataWriter for LegacyPongPacket {
    async fn write(&self, writer: &mut (impl AsyncWrite + Unpin)) -> Result<()> {
        let mut d = Vec::new();
        let data = format!("{}\0{}\0{}\0{}\0{}", 127, self.server_version, self.motd, self.current_players, self.max_players);
        let length = data.len() + 3; // +3 because the two beginning chars plus zero
        let data = data.encode_utf16().collect::<Vec<_>>();
        let data: Vec<u8> = data.iter().map(|i| [((i>>8)&0xFF) as u8, (i&0xFF) as u8]).flatten().collect();
        // let length = data.len();
        // let length = data.len();
        let length = [(length << 8) as u8, length as u8];
        write_bytes(&mut d, &[0xFF]).await?;
        write_bytes(&mut d, &length).await?;
        write_bytes(&mut d, &[0x00, 0xA7, 0x00, 0x31, 0x00, 0x00]).await?;
        write_bytes(&mut d, &data).await?;
        write_bytes(writer, &d).await?;
        Ok(())
    }
}
impl DataReader for LegacyPingPacket {
    async fn read(reader: &mut (impl AsyncRead + Unpin)) -> Result<Self> {
        let mut data = [0; 3];
        match reader.read_exact(&mut data).await { Ok(_) => Ok(()), Err(_) => Error::NotEnoughtBytes(format!("{}:{}", file!(), line!())).into()}?;
        println!("data: {:?}", data);
        let length = ((data[1] as u16) << 8) | data[2] as u16;
        let length = length;
        println!("length: {length}");
        for i in 0..length {
            println!("i: {i}");
            consume_utf16be_char(reader, line!(), file!()).await?;
        }
        println!("Chars consumed");
        let mut length = [0;2];
        match reader.read_exact(&mut length).await { Ok(_) => Ok(()), Err(_) => Error::NotEnoughtBytes(format!("{}:{}", file!(), line!())).into()}?;
        let length = ((length[0] as u16) << 8) | length[1] as u16;
        let mut data_buf = vec![0; length as usize];
        match reader.read_exact(&mut data_buf).await {
            Ok(_) => (),
            Err(e) => {
                eprintln!("Error: {:?}", e);
                return Error::NotEnoughtBytes(format!("{}:{}", file!(), line!())).into()
            }
        }
        println!("bytes to consume: {length}");
        // consume_n_bytes(reader, length as u64).await?;
        // println!("bytes consumed");
        Ok(Self)
    }
}
impl PacketReader for HandshakePacket {
    async fn read(reader: &mut (impl AsyncRead + Unpin), _length: i32, _packet_id: i32) -> Result<Self> {
        let protocol = VarInt::read(reader).await?;
        let address= String::read(reader).await?;
        let port = UnsignedShort::read(reader).await?;
        let next_state = Enum::read(reader).await?;
        Ok(Self{ protocol, address, port, next_state })
    }
}