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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::fmt;

use debris_llir::{
    llir_nodes::WriteTarget,
    minecraft_utils::{ScoreboardComparison, ScoreboardOperation},
};
use fmt::Display;

use crate::common::{ExecuteComponent, MinecraftCommand, MinecraftRange};

impl fmt::Display for MinecraftCommand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MinecraftCommand::ScoreboardSet { player, value } => {
                write!(f, "scoreboard players set {player} {value}")
            }
            MinecraftCommand::ScoreboardSetEqual { player1, player2 } => {
                write!(f, "scoreboard players operation {player1} = {player2}")
            }
            MinecraftCommand::ScoreboardSetFromResult { player, command } => {
                write!(f, "execute store result score {player} run ")?;
                command.fmt(f)
            }
            MinecraftCommand::ScoreboardOperation {
                player1,
                player2,
                operation,
            } => write!(
                f,
                "scoreboard players operation {player1} {} {player2}",
                fmt_operation(*operation)
            ),
            MinecraftCommand::ScoreboardOperationAdd { player, value } => {
                let (mode, value) = if *value < 0 {
                    ("remove", value * -1)
                } else {
                    ("add", *value)
                };

                write!(f, "scoreboard players {mode} {player} {value}")
            }
            MinecraftCommand::Execute { parts, and_then } => {
                write!(f, "execute ")?;

                for part in parts {
                    part.fmt(f)?;
                    write!(f, " ")?;
                }

                if let Some(and_then) = and_then {
                    write!(f, "run {and_then}")?;
                }
                Ok(())
            }
            MinecraftCommand::Function { function } => write!(f, "function {function}"),
            MinecraftCommand::ScoreboardAdd {
                name,
                criterion,
                json_name,
            } => {
                if let Some(json) = json_name {
                    write!(f, "scoreboard objectives add {name} {criterion} {json}")
                } else {
                    write!(f, "scoreboard objectives add {name} {criterion}")
                }
            }
            MinecraftCommand::ScoreboardRemove { name } => {
                write!(f, "scoreboard objectives remove {name}")
            }
            MinecraftCommand::RawCommand { command } => write!(f, "{command}"),
            MinecraftCommand::JsonMessage { target, message } => match target {
                WriteTarget::Chat => write!(f, "tellraw @a {message}"),
                WriteTarget::Actionbar => write!(f, "title @a actionbar {message}"),
                WriteTarget::Subtitle => write!(f, "title @a subtitle {message}"),
                WriteTarget::Title => write!(f, "title @a title {message}"),
            },
        }
    }
}

impl fmt::Display for ExecuteComponent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ExecuteComponent::IfScoreRelation {
                player1,
                player2,
                comparison,
            } if comparison == &ScoreboardComparison::NotEqual => write!(
                f,
                "unless score {player1} {} {player2}",
                fmt_comparison(ScoreboardComparison::Equal)
            ),
            ExecuteComponent::IfScoreRelation {
                player1,
                player2,
                comparison,
            } => write!(
                f,
                "if score {player1} {} {player2}",
                fmt_comparison(*comparison)
            ),
            ExecuteComponent::IfScoreRange {
                player,
                range: MinecraftRange::NotEqual(val),
            } => {
                write!(
                    f,
                    "unless score {player} matches {}",
                    MinecraftRange::Equal(*val)
                )
            }
            ExecuteComponent::IfScoreRange { player, range } => {
                write!(f, "if score {player} matches {range}")
            }
        }
    }
}

impl Display for MinecraftRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MinecraftRange::NotEqual(_) => panic!("Cannot stringify NotEqual range"),
            MinecraftRange::Equal(val) => write!(f, "{val}"),
            MinecraftRange::Range { from, to } => write!(f, "{from}..{to}"),
            MinecraftRange::Minimum(min) => write!(f, "{min}.."),
            MinecraftRange::Maximum(max) => write!(f, "..{max}"),
        }
    }
}

fn fmt_comparison(comparison: ScoreboardComparison) -> &'static str {
    match comparison {
        ScoreboardComparison::Equal => "=",
        ScoreboardComparison::Less => "<",
        ScoreboardComparison::LessOrEqual => "<=",
        ScoreboardComparison::Greater => ">",
        ScoreboardComparison::GreaterOrEqual => ">=",
        ScoreboardComparison::NotEqual => "!=",
    }
}

fn fmt_operation(operation: ScoreboardOperation) -> &'static str {
    match operation {
        ScoreboardOperation::Plus => "+=",
        ScoreboardOperation::Minus => "-=",
        ScoreboardOperation::Times => "*=",
        ScoreboardOperation::Divide => "/=",
        ScoreboardOperation::Modulo => "%=",
        ScoreboardOperation::Max => ">",
        ScoreboardOperation::Min => "<",
    }
}

#[cfg(test)]
mod tests {
    use std::rc::Rc;

    use debris_llir::{
        llir_nodes::WriteTarget,
        minecraft_utils::{ScoreboardComparison, ScoreboardOperation},
    };

    use crate::common::{
        ExecuteComponent, FunctionIdent, MinecraftCommand, MinecraftRange, ObjectiveCriterion,
        ScoreboardPlayer,
    };

    #[test]
    fn test_scoreboard_set() {
        let command = MinecraftCommand::ScoreboardSet {
            player: ScoreboardPlayer {
                player: "@s".into(),
                scoreboard: "debris".into(),
            },
            value: 100,
        };

        assert_eq!(command.to_string(), "scoreboard players set @s debris 100");
    }

    #[test]
    fn test_scoreboard_set_equal() {
        let command = MinecraftCommand::ScoreboardSetEqual {
            player1: ScoreboardPlayer {
                player: "@s".into(),
                scoreboard: "debris".into(),
            },
            player2: ScoreboardPlayer {
                player: "foo".into(),
                scoreboard: "debris.0".into(),
            },
        };

        assert_eq!(
            command.to_string(),
            "scoreboard players operation @s debris = foo debris.0"
        );
    }

    #[test]
    fn test_scoreboard_set_from_result() {
        let command1 = MinecraftCommand::ScoreboardSetEqual {
            player1: ScoreboardPlayer {
                player: "@s".into(),
                scoreboard: "debris".into(),
            },
            player2: ScoreboardPlayer {
                player: "foo".into(),
                scoreboard: "debris.0".into(),
            },
        };

        let command = MinecraftCommand::ScoreboardSetFromResult {
            player: ScoreboardPlayer {
                player: "me".into(),
                scoreboard: "debris".into(),
            },
            command: Box::new(command1),
        };

        assert_eq!(
            command.to_string(),
            "execute store result score me debris run scoreboard players operation @s debris = foo debris.0"
        );
    }

    #[test]
    fn test_scoreboard_operation() {
        let command = MinecraftCommand::ScoreboardOperation {
            player1: ScoreboardPlayer {
                player: "value_1".into(),
                scoreboard: "main".into(),
            },
            operation: ScoreboardOperation::Modulo,
            player2: ScoreboardPlayer {
                player: "value_2".into(),
                scoreboard: "main".into(),
            },
        };

        assert_eq!(
            command.to_string(),
            "scoreboard players operation value_1 main %= value_2 main"
        );
    }

    #[test]
    fn test_scoreboard_operation_add() {
        let command = MinecraftCommand::ScoreboardOperationAdd {
            player: ScoreboardPlayer {
                player: "value_1".into(),
                scoreboard: "main".into(),
            },
            value: 15,
        };

        assert_eq!(
            command.to_string(),
            "scoreboard players add value_1 main 15"
        );
    }

    #[test]
    fn test_scoreboard_operation_add_neg() {
        let command = MinecraftCommand::ScoreboardOperationAdd {
            player: ScoreboardPlayer {
                player: "value_1".into(),
                scoreboard: "main".into(),
            },
            value: -12,
        };

        assert_eq!(
            command.to_string(),
            "scoreboard players remove value_1 main 12"
        );
    }

    #[test]
    fn test_execute() {
        let command = MinecraftCommand::Execute {
            parts: vec![
                ExecuteComponent::IfScoreRelation {
                    comparison: ScoreboardComparison::GreaterOrEqual,
                    player1: ScoreboardPlayer {
                        player: "val_1".into(),
                        scoreboard: "main".into(),
                    },
                    player2: ScoreboardPlayer {
                        player: "val_2".into(),
                        scoreboard: "main2".into(),
                    },
                },
                ExecuteComponent::IfScoreRelation {
                    comparison: ScoreboardComparison::NotEqual,
                    player1: ScoreboardPlayer {
                        player: "val_2".into(),
                        scoreboard: "main2".into(),
                    },
                    player2: ScoreboardPlayer {
                        player: "val_1".into(),
                        scoreboard: "main".into(),
                    },
                },
            ],
            and_then: Some(Box::new(MinecraftCommand::RawCommand {
                command: "do_something".into(),
            })),
        };

        assert_eq!(command.to_string(), "execute if score val_1 main >= val_2 main2 unless score val_2 main2 = val_1 main run do_something");
    }

    #[test]
    fn test_execute_no_command() {
        let command = MinecraftCommand::Execute {
            parts: vec![ExecuteComponent::IfScoreRelation {
                comparison: ScoreboardComparison::GreaterOrEqual,
                player1: ScoreboardPlayer {
                    player: "val_1".into(),
                    scoreboard: "main".into(),
                },
                player2: ScoreboardPlayer {
                    player: "val_2".into(),
                    scoreboard: "main2".into(),
                },
            }],
            and_then: None,
        };

        assert_eq!(
            command.to_string(),
            "execute if score val_1 main >= val_2 main2 "
        );
    }

    #[test]
    fn test_function() {
        let command = MinecraftCommand::Function {
            function: Rc::new(FunctionIdent {
                is_collection: false,
                namespace: "debris".into(),
                path: "foo/bar".to_string(),
            }),
        };

        assert_eq!(command.to_string(), "function debris:foo/bar");
    }

    #[test]
    fn test_scoreboard_add() {
        let command = MinecraftCommand::ScoreboardAdd {
            name: "foo".into(),
            criterion: ObjectiveCriterion::Dummy,
            json_name: None,
        };

        assert_eq!(command.to_string(), "scoreboard objectives add foo dummy");
    }

    // #[test]
    // fn test_scoreboard_add_json_name() {
    //     let command = MinecraftCommand::ScoreboardAdd {
    //         name: "foo".into(),
    //         criterion: ObjectiveCriterion::Other("Health".to_string()),
    //         json_name: Some(r#"{"text":"foo", "color":"green"}"#.to_string()),
    //     };

    //     assert_eq!(
    //         command.stringify(),
    //         r#"scoreboard objectives add foo Health {"text":"foo", "color":"green"}"#
    //     )
    // }

    #[test]
    fn test_scoreboard_remove() {
        let command = MinecraftCommand::ScoreboardRemove { name: "foo".into() };

        assert_eq!(command.to_string(), "scoreboard objectives remove foo");
    }

    #[test]
    fn test_raw_command() {
        let command = MinecraftCommand::RawCommand {
            command: "Hallo Welt".into(),
        };

        assert_eq!(command.to_string(), "Hallo Welt");
    }

    #[test]
    fn test_write_message() {
        let command = MinecraftCommand::JsonMessage {
            target: WriteTarget::Actionbar,
            message: "Hello World".to_string(),
        };

        assert_eq!(command.to_string(), "title @a actionbar Hello World");
    }

    #[test]
    fn test_write_message_chat() {
        let command = MinecraftCommand::JsonMessage {
            target: WriteTarget::Chat,
            message: "Hello World".to_string(),
        };

        assert_eq!(command.to_string(), "tellraw @a Hello World");
    }

    #[test]
    fn test_stringify_execute_part_score_relation() {
        let part = ExecuteComponent::IfScoreRelation {
            comparison: ScoreboardComparison::Greater,
            player1: ScoreboardPlayer {
                player: "val_1".into(),
                scoreboard: "main".into(),
            },
            player2: ScoreboardPlayer {
                player: "val_2".into(),
                scoreboard: "main2".into(),
            },
        };

        assert_eq!(part.to_string(), "if score val_1 main > val_2 main2");
    }

    #[test]
    fn test_stringify_execute_part_score_range() {
        let part = ExecuteComponent::IfScoreRange {
            player: ScoreboardPlayer {
                player: "val_1".into(),
                scoreboard: "main".into(),
            },
            range: MinecraftRange::Range { from: 0, to: 99 },
        };

        assert_eq!(part.to_string(), "if score val_1 main matches 0..99");
    }

    #[test]
    fn test_stringify_execute_part_score_range_greater() {
        let part = ExecuteComponent::IfScoreRange {
            player: ScoreboardPlayer {
                player: "val_1".into(),
                scoreboard: "main".into(),
            },
            range: MinecraftRange::Minimum(4),
        };

        assert_eq!(part.to_string(), "if score val_1 main matches 4..");
    }

    #[test]
    fn test_stringify_execute_part_score_range_not() {
        let part = ExecuteComponent::IfScoreRange {
            player: ScoreboardPlayer {
                player: "val_1".into(),
                scoreboard: "main".into(),
            },
            range: MinecraftRange::NotEqual(-1),
        };

        assert_eq!(part.to_string(), "unless score val_1 main matches -1");
    }
}