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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/// Macro for generating structures that can be encoded and decoded from bytes
/// (DONT USE THIS FOR GROUPS USE `tdf_group` because they require extra bytes)
///
/// You can only use types that implement Codec the ones implemented
/// by this library are
///
/// Example Usage
/// ```
///
/// use blaze_pk::{packet, Blob};
///
/// packet! {
///     struct Test {
///         TEST: u16,
///         ALT: String,
///         BYT: Blob
///     }
/// }
///
/// ```
///
/// Generated structs can then be used as packet body's when
/// creating packets
///
#[macro_export]
macro_rules! packet {
    (
        struct $name:ident {
            $(
                $tag:ident $field:ident: $ty:ty
            ),* $(,)?
        }

    ) => {
        #[derive(Debug)]
        pub struct $name {
            $(pub $field: $ty),*
        }

        /// Trait fitting implementations
        impl $crate::Codec for $name {

            fn encode(&self, output: &mut Vec<u8>) {
                $($crate::encode_field!(output, $tag, &self.$field, $ty);)*
            }

            fn decode(reader: &mut $crate::Reader) -> $crate::CodecResult<Self>  {
                $($crate::decode_field!(reader, $tag, $field, $ty);)*
                Ok(Self {
                    $($field),*
                })
            }
        }
    };
}

#[macro_export]
macro_rules! tag_group {
    ($output:ident, $tag:literal, $content:block) => {
        $crate::tag_group_start($output, $tag);

        {
            $content
        }

        $crate::tag_group_end($output);
    };
}

/// Macro for generating encoding for a field with with a tag and field
#[macro_export]
macro_rules! encode_field {
    ($output:ident, $tag:ident, $field:expr, $ty:ty) => {
        $crate::Tag::encode_from(stringify!($tag), &(<$ty>::value_type()), $output);
        <$ty>::encode($field, $output);
    };
}

#[macro_export]
macro_rules! encode_zero {
    ($output:ident, $tag:ident) => {
        $crate::Tag::encode_from(stringify!($tag), &$crate::ValueType::VarInt, $output);
        $output.push(0);
    };
}

#[macro_export]
macro_rules! encode_empty_str {
    ($output:ident, $tag:ident) => {
        $crate::Tag::encode_from(stringify!($tag), &$crate::ValueType::String, $output);
        $output.push(1);
        $output.push(0);
    };
}

/// Macro for generating decoding for a field and tag
#[macro_export]
macro_rules! decode_field {
    ($reader:ident, $tag:ident, $field:ident, $ty:ty) => {
        let $field = $crate::Tag::expect::<$ty>($reader, stringify!($tag))
            .map_err(|err| $crate::CodecError::DecodeFail(stringify!($field), Box::new(err)))?;
    };
}

/// Macro for generating group structures prefixing the struct with (2)
/// indicates that when encoding a byte value of two should be placed
/// at the start.
#[macro_export]
macro_rules! group {
    (
        struct $name:ident {
            $(
                $tag:ident $field:ident: $ty:ty
            ),* $(,)?
        }
    ) => {
        #[derive(Debug)]
        #[allow(non_snake_case)]
        pub struct $name {
            $(pub $field: $ty),*
        }

        impl $crate::Codec for $name {

            fn encode(&self, output: &mut Vec<u8>) {
                $($crate::encode_field!(output, $tag, &self.$field, $ty);)*
                output.push(0)
            }

            fn decode(reader: &mut $crate::Reader) -> $crate::CodecResult<Self> {
                $crate::Tag::take_two(reader)?;
                $($crate::decode_field!(reader, $tag, $field, $ty);)*
                $crate::Tag::discard_group(reader)?;
                Ok(Self {
                    $($field),*
                })
            }

            fn value_type() -> $crate::ValueType {
                $crate::ValueType::Group
            }
        }
    };
    (
        (2) struct $name:ident {
            $(
                $tag:ident $field:ident: $ty:ty
            ),* $(,)?
        }
    ) => {
        #[derive(Debug)]
        #[allow(non_snake_case)]
        pub struct $name {
            $(pub $field: $ty),*
        }

        impl $crate::Codec for $name {

            fn encode(&self, output: &mut Vec<u8>) {
                output.push(2);
                $($crate::encode_field!(output, $tag, &self.$field, $ty);)*
                output.push(0);
            }

            fn decode(reader: &mut $crate::Reader) -> $crate::CodecResult<Self> {
                $crate::Tag::take_two(reader)?;
                $($crate::decode_field!(reader, $tag, $field, $ty);)*
                $crate::Tag::discard_group(reader)?;
                Ok(Self {
                    $($field),*
                })
            }

            fn value_type() -> $crate::ValueType {
                $crate::ValueType::Group
            }
        }
    };
}

/// Macro for defining component enums for packet identification
///
/// ```
///use blaze_pk::define_components;
///define_components! {
///    Authentication (0x00) {
///        Key (0x00)
///        Alert (0x02)
///        Value (0x23)
///    }
///
///    Other (0x1) {
///        Key (0x00)
///        Alert (0x02)
///    }
/// }
/// ```
#[macro_export]
macro_rules! define_components {
    (

        $(
            $component:ident ($component_value:literal) {
                $(
                    $command:ident ($command_value:literal)
                )*

                $(;
                    notify {

                        $(
                            $command_notify:ident ($command_notify_value:literal)
                        )*

                    }
                )?
            }
        )*
    ) => {
        #[derive(Debug, Eq, PartialEq)]
        pub enum Components {
            $($component($component),)*
            Unknown(u16, u16)
        }

        impl $crate::PacketComponents for Components {


            fn values(&self)-> (u16, u16) {
                use $crate::PacketComponent;
                match self {
                    $(
                        Self::$component(command) => ($component_value, command.command()),
                    )*
                    Self::Unknown(a, b) => (*a, *b),
                }
            }

            fn from_values(component: u16, command: u16, notify: bool) -> Self {
                use $crate::PacketComponent;
                match component {
                    $($component_value => Self::$component($component::from_value(command, notify)),)*
                    _ => Self::Unknown(component, command),
                }
            }
        }

        $(
            #[derive(Debug, Eq, PartialEq)]
            pub enum $component {
                $($command,)*
                $($($command_notify,)*)?
                Unknown(u16)
            }

            impl $crate::PacketComponent for $component {
                fn command(&self) -> u16 {
                    match self {
                        $(Self::$command => $command_value,)*
                        $(
                            $(Self::$command_notify => $command_notify_value,)*
                        )?
                        Self::Unknown(value) => *value,
                    }
                }

                fn from_value(value: u16, notify: bool) -> Self {
                    if notify {
                        match value {
                            $($($command_notify_value => Self::$command_notify,)*)?
                            value => Self::Unknown(value)
                        }
                    } else  {
                        match value {
                            $($command_value => Self::$command,)*
                            value => Self::Unknown(value)
                        }
                    }
                }
            }
        )*
    };
}

#[cfg(test)]
mod test {
    use crate::{Codec, Reader};
    use crate::{TdfMap, TdfOptional, VarIntList};

    define_components! {
        Authentication (0x1) {

            SuperLongNameThisIs (0x2)

        }
    }

    packet! {
        struct TestStruct {
            AA aa: u8,
            AB ab: u16,
            AC ac: String,
            AD ad: Vec<u8>,
            AE ae: MyGroup,
            AF af: Vec<String>,
            AG ag: Vec<MyGroup>,
            AH ah: TdfMap<String, String>,
            AI ai: TdfOptional<String>,
            AK ak: VarIntList<u32>,
            AL al: (u8, u8),
            AM am: (u32, u32, u32)
        }
    }

    group! {
        struct MyGroup {
            ABCD abcd: String
        }
    }

    #[test]
    fn test() {
        let mut map = TdfMap::<String, String>::new();
        map.insert("Test", "Map");
        map.insert("Other", "Test");
        map.insert("New", "Value");
        let str = TestStruct {
            aa: 254,
            ab: 12,
            ac: String::from("test"),
            ad: vec![0, 5, 12, 5],
            ae: MyGroup {
                abcd: String::from("YES"),
            },
            af: vec![String::from("ABC"), String::from("Abced")],
            ag: vec![
                MyGroup {
                    abcd: String::from("YES1"),
                },
                MyGroup {
                    abcd: String::from("YES2"),
                },
            ],
            ah: map,
            ai: TdfOptional::<String>::None,
            ak: VarIntList(vec![1]),
            al: (5, 236),
            am: (255, 6000, 6743),
        };

        let out = str.encode_bytes();

        println!("{out:?}");

        let mut reader = Reader::new(&out);
        let str_out = TestStruct::decode(&mut reader).unwrap();
        println!("{str_out:?}");

        assert_eq!(str.ab, str_out.ab);
        assert_eq!(str.ac, str_out.ac);
        assert_eq!(str.ad, str_out.ad);
    }
}