thrustin 1.0.1

xperience epic adventures by THRUSTING some THRUSTERS into THRUSTEES https://THRUSTIN.rs. E
Documentation
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
use crate::lobby_game::LobbyGame;
use crate::player::{Player, PlayerState};
use crate::player_game::PlayerGame;
use crate::thrust::Deck;
use std::cell::{RefCell, RefMut};
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::u8;
use std::usize;

#[derive(Clone, PartialEq, Debug)]
pub enum LobbyState {
    Playing,
    Waiting,
}

#[derive(Clone, Debug)]
pub struct Lobby {
    game: LobbyGame,
    //max hand size
    hand_size: u8,
    //host of lobby
    host: Rc<RefCell<Player>>,
    // How many house THRUSTS are being used
    house: usize,
    //list of players
    list: Vec<Rc<RefCell<Player>>>,
    //lobby id
    id: i32,
    //max number of players
    max_players: usize,
    //points
    max_points: u8,
    max_thrustee_choices: u8,
    //optional password for lobby
    pw: String,
    //lobby state
    state: LobbyState,
}

impl Lobby {
    fn build_thrusters_messages(thrusters: &Vec<String>) -> Vec<String> {
        let mut messages = vec!["Here are your THRUSTERS:".to_string()];
        for (index, thruster) in thrusters.iter().enumerate() {
            // Convert from 0-indexing to 1-indexing
            messages.push(format!("{}. {}", &index + 1, &thruster).to_string());
        }
        messages
    }

    fn get_joining_pl_state(
        lob: &mut Lobby,
        pl: &mut RefMut<Player>,
        messages: &mut Vec<String>,
        pl_rc: &Rc<RefCell<Player>>,
    ) -> Option<PlayerState> {
        // Distribute thrusters to player
        lob.refill_thrusters(pl);

        let mut wait: bool = false;

        // If lobby was empty before this guy joined, then they become THRUSTEE, otherwise, basically do what normal join_lobby does (yea this is fucked fk me doggo)
        if lob.list.len() == 0 {
            pl.state = PlayerState::Choosing;
            let mut messages =
                vec!["Welcome to the 『Endless Lobby』, big doggo. You lucky, family, you are THRUSTEE!!!!.. . Choose now...    .".to_string()];
            messages.extend(lob.print_thrustee_choices());
            pl.send_messages(&messages);
            pl.lobby = lob.id;
            lob.list.push(pl_rc.clone());
            lob.game.thrustee = 0;
            return None; //dude lmao
        } else {
            Lobby::handle_join_cases(&pl, &lob, &mut wait, messages);
        }

        if wait {
            return Some(PlayerState::Waiting);
        } else {
            return Some(PlayerState::Playing);
        }
    }

    fn handle_join_cases(
        pl: &RefMut<Player>,
        lob: &Lobby,
        wait: &mut bool,
        messages: &mut Vec<String>,
    ) {
        let thrustee = lob.list[lob.game.thrustee].borrow();

        match thrustee.state {
            PlayerState::Choosing => {
                *wait = true;
                messages.push(format!(
                    "THRUSTEE {} is currently CHOOSING next THRUSTEE. Hold on tight!",
                    &thrustee.name
                ));
            }

            PlayerState::Deciding => {
                messages.push(format!(
                    "This is {}'s THRUSTEE for you: {}<br/>",
                    &thrustee.name, &lob.game.current_thrustee
                ));
                messages.extend(Lobby::build_thrusters_messages(&pl.game.deck.thrusters));
            }

            _ => (),
        }
    }

    fn leave(&mut self, pl: Rc<RefCell<Player>>) {
        // borrow shenanigans
        {
            let pl = pl.borrow();

            // Much easier to clear single person lobby than multiple
            if self.list.len() == 1 {
                self.list.clear();
            } else {
                let pl_ind = self.search_token(pl.token).unwrap();
                let next_ind = (pl_ind + 1) % self.list.len();
                // This needs to be calculated as if pl has been removed
                let next_thrustee = pl_ind % (self.list.len() - 1);

                // Set up messages
                let mut messages = vec![String::from(format!("{} left the lobby..", pl.name))];
                // Handle if player is host
                if pl.token == self.host.borrow().token {
                    self.host = self.list[next_ind].clone();
                    messages.push(String::from(format!(
                        "Chief left so now we got a new one --> {}",
                        self.host.borrow().name
                    )));
                }

                let mut did_thrustee_change = false;
                // Handle if player is Choosing
                if pl.state == PlayerState::Choosing {
                    self.game.thrustee = next_thrustee;
                    did_thrustee_change = true;
                    // Next player chooses and replenish cards
                    let mut next = self.list[next_ind].borrow_mut();
                    next.state = PlayerState::Choosing;
                    messages.push(String::from(format!(
                        "Lol yo bro 'cause the THRUSTEE left {} is choosin' the next THRUSTEE now!",
                        next.name
                    )));
                }
                // Handle if player is Deciding
                else if pl.state == PlayerState::Deciding {
                    self.game.thrustee = next_thrustee;
                    did_thrustee_change = true;
                    // Next player decides
                    let mut next = self.list[next_ind].borrow_mut();
                    next.state = PlayerState::Deciding;
                    messages.push(String::from(format!("Lmao the THRUSTEE left and you're next in line, so {} gets to decide which THRUST wins lmfao.", next.name)));
                }
                // Handle if player is Normal
                else {
                    if pl_ind < self.game.thrustee {
                        self.game.thrustee = self.game.thrustee - 1;
                    }
                }

                // Remove player after we are done with managing player state
                self.list.remove(pl_ind);

                // Send appropriate message
                for pl_rc in &self.list {
                    let pl = pl_rc.borrow();
                    if did_thrustee_change && pl.state == PlayerState::Choosing {
                        let mut thrustee_messages = messages.clone();
                        // Add a linebreak for better visibility
                        thrustee_messages.last_mut().unwrap().push_str("<br/>");
                        // Notify new Choosing THRUSTEE of choices
                        thrustee_messages.extend(self.print_thrustee_choices());
                        pl.send_messages(&thrustee_messages);
                    } else {
                        pl.send_messages(&messages);
                    }
                }
            }
        }

        // Player mut and specific operations
        let mut pl = pl.borrow_mut();
        pl.lobby = -1;
        pl.state = PlayerState::OutOfLobby;
        pl.send_message("You have been leaved from the lobby okay!");
    }

    fn new(
        player: &Rc<RefCell<Player>>,
        id: i32,
        pass: &str,
        max_players: usize,
        max_points: u8,
        house: usize,
    ) -> Lobby {
        Lobby {
            hand_size: 5,
            id,
            max_points,
            game: LobbyGame::new(),
            host: player.clone(),
            house,
            list: Vec::new(),
            max_players,
            max_thrustee_choices: 3,
            pw: String::from(pass),
            state: LobbyState::Waiting,
        }
    }

    fn print_thrustee_choices(&self) -> Vec<String> {
        let mut messages = vec!["your THRUSTEE Choices:".to_string()];
        for (index, thrustee) in self.game.thrustee_choices.iter().enumerate() {
            // Convert from 0-indexing to 1-indexing
            messages.push(format!("{}. {}", &index + 1, &thrustee).to_string());
        }
        messages
    }

    fn search_token(&self, token: u32) -> Option<usize> {
        for (i, pl) in self.list.iter().enumerate() {
            let tok = pl.borrow().token;
            if tok == token {
                return Some(i);
            }
        }

        None
    }

    fn send_message(&self, message: &str) {
        for pl in &self.list {
            pl.borrow().send_message(&message);
        }
    }

    fn send_messages(&self, messages: Vec<String>) {
        for pl in &self.list {
            pl.borrow().send_messages(&messages);
        }
    }

    // refill_thrusters() but does not clear deck beforehand
    fn refill_remaining_thrusters(&mut self, pl: &mut Player) {
        // Distribute thrusters to player to fill thrusters
        for _ in pl.game.deck.thrusters.len()..self.hand_size as usize {
            if let Some(card) = self.game.deck.thrusters.pop() {
                pl.game.deck.thrusters.push(card);
            } else {
                // Refill thrusters if empty
                self.game.deck.thrusters = self.game.deck_reference.thrusters.clone();
                self.game.deck.shuffle_thrusters();
                pl.game
                    .deck
                    .thrusters
                    .push(self.game.deck.thrusters.pop().unwrap());
            }
        }
    }

    fn refill_thrustees(&mut self) {
        // Setup new thrustee choices
        for _ in 0..self.max_thrustee_choices {
            if let Some(card) = self.game.deck.thrustees.pop() {
                self.game.thrustee_choices.push(card);
            } else {
                self.game.deck.thrustees = self.game.deck_reference.thrustees.clone();
                self.game.deck.shuffle_thrustees();
                self.game
                    .thrustee_choices
                    .push(self.game.deck.thrustees.pop().unwrap());
            }
        }
    }

    fn refill_thrusters(&mut self, pl: &mut Player) {
        // Clear dude's deck beforehand
        pl.game.deck.thrusters.clear();
        self.refill_remaining_thrusters(pl);
    }

    pub fn end(&mut self, pl: Rc<RefCell<Player>>) {
        {
            let pl = pl.borrow();
            if !self.is_host(pl.token) {
                pl.send_message(&format!(
                    "Only chief shall have the privilege to end the game."
                ));
                return;
            }
        }

        self.end_game("Yo guys, the game's been manually ended by the chief almighty. Yall have been returned to the lobby setup area.".to_string());
    }

    pub fn end_game(&mut self, end_message: String) {
		// Each player will have a unique message depending on EXP gained & whether authenticated or not. End_messages contains each unique one
		let end_messages: Vec<String> = self.give_players_exp(end_message);
        self.state = LobbyState::Waiting;
        // Change players to inlobby state and send respective end_message to each. 
		// Assumes playerlist is accessed in same order as give_players_exp loop does
		for i in 0..end_messages.len() {
			let mut player = self.list[i].borrow_mut();
			player.state = PlayerState::InLobby;
			player.send_message(&end_messages[i]);
		}
    }

	pub fn give_players_exp(&mut self, end_message: String) -> Vec<String> {
		let points_in_lobby = self.points_in_lobby();
		let num_player = self.list.len();
		let mut messages = vec![end_message; self.list.len()];
		let mut level_messages = vec![];

		for i in 0..self.list.len() {
			let mut player = self.list[i].borrow_mut();
			if player.is_authenticated {
				let mut exp_gained = 0;
				let points_won = player.game.points;

				// if winner
				if points_won >= self.max_points {
					exp_gained += points_in_lobby + num_player as u8;
				}
				else {
					exp_gained += points_won + num_player as u8;
				}

				player.up_exp(exp_gained as i32);
				messages[i] = format!("{}<br/>Bro congratulation! You have receive {} experience points, congratulation!", messages[i], exp_gained);

				let mut leveled = false;
				// Possible to level multiple times in earlier levels so I used While Loop
				while player.level != 100 && self.ready_to_level(player.level, player.exp) {
					leveled = true;
					let current_level: i32 = player.level;
					player.up_level(self.get_exp_from_level(current_level));
				}

				if leveled {
					level_messages.push(format!(
						"{} has LEVELED UP!!!! Congratulation, {}, you are now level {}!!", 
						player.name, player.name, player.level));
				}
			}
		}
		let level_messages = level_messages.join("<br/>");
		// Append leveling messages to individual players' EXP gain messages
		for i in 0..messages.len() {
			messages[i] = format!("{}<br/>{}", messages[i], level_messages);
		}
		return messages;
	}

	pub fn ready_to_level(&self, level: i32, exp: i32) -> bool {
		return exp >= self.get_exp_from_level(level);
	}

	pub fn get_exp_from_level(&self, level: i32) -> i32 {
		let exponent: f32 = 2.15;
		let level = level as f32;
    	level.powf(exponent).round() as i32
	}

	pub fn points_in_lobby(&self) -> u8 {
		let mut total_points = 0;
		for rc in &self.list {
			let player = rc.borrow();
			total_points += player.game.points;
		}
		return total_points
	}

    pub fn choose(&mut self, input: Vec<&str>, pl: Rc<RefCell<Player>>) {
        if input.len() != 2 {
            pl.borrow().send_message("ya need to pick a NUMERIC, Boy");
            return;
        }

        // Use i32 so index-1 doesn't underflow
        match input[1].parse::<i32>() {
            Ok(index) => {
                // Convert from 1-indexing to 0-indexing
                let index = index - 1;
                if index < self.max_thrustee_choices as i32 && index > -1 {
                    // Scope refcell borrow
                    let name;
                    {
                        let mut pl = pl.borrow_mut();

                        // Removed selected choice
                        let card = self.game.thrustee_choices.remove(index as usize);
                        self.game.current_thrustee = card;
                        pl.state = PlayerState::Deciding;

                        // Refill choices
                        self.game.thrustee_choices.clear();
                        self.refill_thrustees();
                        name = pl.name.clone();
                    }

                    // Notify players
                    for (i, pl_rc) in self.list.iter().enumerate() {
                        let mut pl = pl_rc.borrow_mut();
                        let mut messages = vec![format!(
                            "{} has chosen this new THRUSTEE:<br/>{}<br/>",
                            name, &self.game.current_thrustee
                        )
                        .to_string()];

                        // Change Waiting players to Playing
                        if pl.state == PlayerState::Waiting {
                            pl.state = PlayerState::Playing;
                        }

                        if i == self.game.thrustee {
                            messages.push(
                                "get Ready to decide best THRUSTER for THRUSTING!".to_string(),
                            );
                            pl.send_messages(&messages);
                        } else {
                            messages
                                .extend(Lobby::build_thrusters_messages(&pl.game.deck.thrusters));
                            pl.send_messages(&messages);
                        }
                    }
                } else {
                    pl.borrow().send_message("That shit's out of bound bro");
                }
            }
            _ => {
                pl.borrow().send_message(
                    "That is an invalid parameter my chieftain, use an index instead dawggo.",
                );
            }
        };
    }

    pub fn decide(&mut self, input: Vec<&str>, pl: Rc<RefCell<Player>>) {
        if input.len() != 2 {
            pl.borrow().send_message("ya need to pick a numbert boi");
            return;
        }

        // Use i32 so index-1 doesn't underflow
        match input[1].parse::<i32>() {
            Ok(index) => {
                // Convert from 1-indexing to 0-indexing
                let index = index - 1;
                if index < self.game.current_thrusts.len() as i32 && index > -1 {
                    // Because of multiple mutable references
                    let (name, token, chosen_thrust) = {
                        let mut pl = pl.borrow_mut();
                        let name = pl.name.clone();

                        // Get chosen thrust
                        let (token, chosen_thrust) = self
                            .game
                            .current_thrusts
                            .get(&(index as usize))
                            .unwrap()
                            .clone();

                        // Clear thrust values
                        self.game.current_thrusts.clear();
                        self.game.thrusted_players.clear();

                        // Set current THRUSTEE to THRUSTER state
                        pl.state = PlayerState::Waiting;
                        (name, token, chosen_thrust)
                    };

                    let (chosen_thruster_pts, chosen_thruster_name) = {
                        // Assign picked thruster a point
                        match self.search_token(token) {
                            Some(index) => {
                                let (pts, winner) = {
                                    let mut chosen_thruster = self.list[index].borrow_mut();
                                    chosen_thruster.game.points += 1;
                                    chosen_thruster.up_points_gained();
                                    (chosen_thruster.game.points.clone(), chosen_thruster.name.clone())
                                };

                                // Check if winner
                                if pts >= self.max_points {
                                    self.list[index].borrow().up_games_won();
                                    let messages = vec![
                                        format!("{} has chosen this THRUSTER as the chosen THRUST, bois:<br/>{}<br/>", &name, &chosen_thrust),
                                        format!("Congratulations, {}! You're Winner! Everyone else, You're Loser! Game has been put into waiting state, THRUSTIN'ers!<br/>",  winner)
                                    ];
                                    self.end_game(messages.join("<br/>"));
                                    return;
                                }
                                (pts, winner)
                            }
                            None => (0, String::from("[[[THE GUY WHO LEFT (look imma be real it's easier right now for me to jam some placeholder text here than properly handle THRUSTERS who leave the game after THRUSTING yeah aite we're just gonna clear his points)]]]"))
                        }
                    };

                    // Assign next THRUSTEE
                    self.game.thrustee = (self.game.thrustee + 1) % self.list.len();

                    // Initialized outside so player.name and chosen_thrust can be kept
                    let common = vec![format!(
                        "{} has chosen this THRUSTER as the chosen THRUST, bois:<br/>{}<br/>",
                        &name, &chosen_thrust
                    )
                    .to_string()];

                    let thrustee_name = self.list[self.game.thrustee].borrow().name.clone();
                    for (i, pl) in self.list.iter().enumerate() {
                        let mut messages = common.clone();

                        messages.push(format!(
                            "The winning THRUSTER, {} now has {}/{} point(s)! Watch out!<br/>",
                            &chosen_thruster_name, &chosen_thruster_pts, self.max_points
                        ));

                        // If THRUSTEE, then set him up to be choosing next shit
                        if i == self.game.thrustee {
                            let mut thrustee_player = pl.borrow_mut();
                            thrustee_player.state = PlayerState::Choosing;
                            messages.push(
                                "You are the neXt THRUSTEE! GetT ready to CHOOSE a good THRUSTEE!"
                                    .to_string(),
                            );
                            messages.extend(self.print_thrustee_choices());
                        } else {
                            let mut thruster_player = pl.borrow_mut();
                            // Set players to Waiting so they can't submit THRUSTER after THRUST is already chosen
                            thruster_player.state = PlayerState::Waiting;
                            messages.push(format!(
                                "{} is choosing.... get rdy to THRUST.....",
                                &thrustee_name
                            ));
                        }
                        pl.borrow().send_messages(&messages);
                    }
                } else {
                    pl.borrow().send_message("That shit's out of bound bro");
                }
            }
            _ => {
                pl.borrow()
                    .send_message("That is an invalid parameter, use an index instead");
            }
        };
    }

    pub fn host(&mut self, input: Vec<&str>, pl: Rc<RefCell<Player>>) {
        let pl = pl.borrow();
        if !self.is_host(pl.token) {
            pl.send_message("Only chief can change the chief!");
            return;
        }

        if input.len() != 2 {
            pl.send_message("Who's the new chief tho");
            return;
        }

        let new_host = input[1];
        if self.host.borrow().name == new_host {
            pl.send_message("You're already chief!!");
            return;
        }

        for players_ in self.list.iter() {
            let players = players_.borrow();
            if players.name == new_host {
                self.host = players_.clone();
                players.send_message("You are now chief!");
                pl.send_message(&format!("{} is now chief!", players.name));
                return;
            }
        }

        pl.send_message("Player not in lobby.");
    }

    pub fn house(&mut self, input: Vec<&str>, pl: Rc<RefCell<Player>>) {
        let pl = pl.borrow();
        if !self.is_host(pl.token) {
            pl.send_message(&format!("Only chief can decide whether or not to use the house (default provided) THRUSTS for THRUSTING!"));
            return;
        }

        if input.len() != 2 {
            pl.send_message("Hello, you need to provide a value to the ~.house~ command.");
            return;
        }

        match input[1].to_string().parse::<usize>() {
            Ok(house) => {
                self.house = house;
                pl.send_message(&format!("House THRUSTS usage set to: {}", self.house));
            }

            _ => pl.send_message(&"Failed house command... only positive numbers dude!!!"),
        }
    }

    pub fn info(&self, pl: Rc<RefCell<Player>>) {
        let pl = pl.borrow();
        let mut info = Vec::new();
        info.push(format!("\\\\Lobby info//"));
        info.push(format!("ID: {}", self.id));
        if self.is_host(pl.token) {
            info.push(format!(
                "***(Only chief [that's you!] may see this!) Password: {}",
                self.pw
            ));
        }
        info.push(format!("Chief: {}", self.host.borrow().name));
        info.push(format!("Players: {}/{}", self.list.len(), self.max_players));
        info.push(format!("Max points? {}", self.max_points));
        info.push(format!("House THRUSTS? {}", self.house));
        info.push(format!("THRUSTEES? {}", self.max_thrustee_choices));
        info.push(format!("THRUSTERS? {}", self.hand_size));
        pl.send_messages(&info);
    }

    pub fn is_host(&self, player: u32) -> bool {
        if self.host.borrow().token == player {
            return true;
        } else if let Some(ind) = self.search_token(player) {
            return self.list[ind].borrow().is_chieftain();
        }
        false
    }

    pub fn kick(&mut self, input: Vec<&str>, pl: Rc<RefCell<Player>>) {
        // Scope guards to avoid borrow panic when THRUSTEE is kicked
        let kick_ind = {
            let mut kick_ind = -1;
            let pl = pl.borrow();
            if !self.is_host(pl.token) {
                pl.send_message("Only chief can kick em!");
                return;
            }

            if input.len() != 2 {
                pl.send_message("who we kickkin? TELL ME!");
                return;
            }

            let kick = input[1];
            if self.host.borrow().name == kick {
                pl.send_message("u cant kick ursel!!");
                return;
            }

            for (i, players) in self.list.iter().enumerate() {
                let players = players.borrow();
                if players.name == kick {
                    kick_ind = i as i32;
                    break;
                }
            }
            kick_ind
        };

        if kick_ind >= 0 {
            self.leave(self.list[kick_ind as usize].clone());
            return;
        }

        let pl = pl.borrow();
        pl.send_message("Player not in lobby.");
    }

    pub fn join(input: Vec<&str>, pl: Rc<RefCell<Player>>, lobby: &mut HashMap<i32, Lobby>) {
        if input.len() < 2 {
            pl.borrow().send_message("Lobby name required!");
            return;
        }

        match input[1].to_string().parse::<i32>() {
            Ok(lobby_id) => {
                let mut pl_mut = pl.borrow_mut();
                let mut messages = Vec::new();
                if let Some(mut lob) = lobby.get_mut(&lobby_id) {
                    // Lobby full check
                    if lob.list.len() >= lob.max_players {
                        pl_mut.send_message("bro this lobbBY is FULLLLL!!");
                        return;
                    }

                    //Lobby Password Check
                    if lob.pw != "" {
                        if input.len() != 3 {
                            pl_mut.send_message("Ya need a password BR)");
                            return;
                        } else if lob.pw != input[2] {
                            pl_mut.send_message("loll wrong pw haha");
                            return;
                        }
                    }
                    messages.push(format!("Joined: {:#?}", &lobby_id));

                    // Reset player game settings on join
                    pl_mut.game = PlayerGame::new();
                    pl_mut.state = if lob.state == LobbyState::Playing {
                        if let Some(state) =
                            Lobby::get_joining_pl_state(&mut lob, &mut pl_mut, &mut messages, &pl)
                        {
                            state
                        } else {
                            return;
                        }
                    } else {
                        PlayerState::InLobby
                    };

                    lob.send_message(&format!("{} has joined the lobby.", pl_mut.name));
                    // adding the new player to lobby
                    pl_mut.lobby = lob.id;
                    pl_mut.up_games_played();
                    lob.list.push(pl.clone());
                    pl_mut.send_messages(&messages);
                } else {
                    pl_mut.send_message("Lobby does not exist.");
                }
            }

            _ => pl
                .borrow()
                .send_message("nibba that is a invalid input my nibba"), //i love rust
        }
    }

    // This feeds into leave()
    // This function is separate from leave() because this also manages removing the lobby if it is empty
    pub fn leave_and_delete(pl: Rc<RefCell<Player>>, lobbies: &mut HashMap<i32, Lobby>) {
        let lobby = pl.borrow().lobby.clone();
        if let Some(lobby) = lobbies.get_mut(&lobby) {
            lobby.leave(pl);
            // Don't delete lobby if it is endless
            if lobby.list.len() == 0 && lobby.id != 0 {
                let id = lobby.id;
                lobbies.remove(&id);
            }
        }
    }

    pub fn list(pl: Rc<RefCell<Player>>, lobbies: &mut HashMap<i32, Lobby>) {
        let pl = pl.borrow();
        let messages = Lobby::list_messages(lobbies);
        pl.send_messages(&messages);
    }

    // This function is extrapolated out so it can be used for all .login, .register, .name, .list commands
    pub fn list_messages(lobbies: &mut HashMap<i32, Lobby>) -> Vec<String> {
        let mut messages = vec![String::from("A current exploration of lobbies that are available to be joined into is as follows below. Simply `.join [ID]` to enter. Lobby 0 is an endless lobby. It's always gonna be there.")];
        for lob in lobbies.values() {
            let state = match &lob.state {
                LobbyState::Playing => "Playing",
                LobbyState::Waiting => "Waiting",
            };
            messages.push(
                format!(
                    "ID: {} | Password: {} | Players: {}/{} | Currently: {}",
                    lob.id,
                    if lob.pw.is_empty() { "" } else { "" },
                    lob.list.len(),
                    lob.max_players,
                    state
                )
                .to_string(),
            );
        }

        messages.sort_unstable_by(|a, b| a.cmp(&b));
        messages
    }

    pub fn make(
        input: Vec<&str>,
        pl_rc: Rc<RefCell<Player>>,
        lobby_id: &mut i32,
        lobbies: &mut HashMap<i32, Lobby>,
    ) {
        let mut pl = pl_rc.borrow_mut();
        if input.len() > 2 {
            pl.send_message("Yo you gotta give the right parameters into .make bro!");
            return;
        }

        let pass = if input.len() > 1 { input[1] } else { "" };

        let mut lobby = Lobby::new(&pl_rc, *lobby_id, pass, 10, 7, 420);
        pl.lobby = lobby_id.clone();
        pl.state = PlayerState::InLobby;
        lobby.list.push(pl_rc.clone());

        lobbies.insert(lobby_id.clone(), lobby.clone());
        pl.send_message(&format!("Created lobby: {}", lobby_id));
        *lobby_id = *lobby_id + 1;
    }

    pub fn make_endless(
        pl_rc: &Rc<RefCell<Player>>,
        lobby_id: &mut i32,
        lobbies: &mut HashMap<i32, Lobby>,
    ) {
        let mut new_lobby = Lobby::new(&pl_rc, 0, "", usize::MAX, u8::MAX, usize::MAX);
        new_lobby.start_endless();

        lobbies.insert(lobby_id.clone(), new_lobby.clone());
    }

    pub fn password(&mut self, input: Vec<&str>, pl: Rc<RefCell<Player>>) {
        let pl = pl.borrow();
        if !self.is_host(pl.token) {
            pl.send_message("only chief sets password!!!");
            return;
        }

        if input.len() != 2 {
            pl.send_message("?? what's the pass boss??");
            return;
        }

        let password = input[1];
        self.pw = password.to_string();
        pl.send_message(&format!(
            "Now, the password has now been locked and loaded, my dude, now it's: {}",
            password
        ));
    }

    pub fn players(&mut self, input: Vec<&str>, pl: Rc<RefCell<Player>>) {
        let pl = pl.borrow();
        if !self.is_host(pl.token) {
            pl.send_message("only chief sets MAXP LAYER!");
            return;
        }

        if input.len() != 2 {
            pl.send_message("ya gotta set the new limit");
            return;
        }

        match input[1].to_string().parse::<usize>() {
            Ok(max) => {
                if max > 64 {
                    pl.send_message(&format!("woah thats 2many people chill! haha"));
                    return;
                }

                if max < self.list.len() {
                    pl.send_message(&format!("too many players in here right now man!"));
                    return;
                }
                self.max_players = max;
                pl.send_message(&format!("max players set to {}", self.max_players));
            }

            _ => pl.send_message(&"only numbers dude!!!"),
        }
    }

    pub fn points(&mut self, input: Vec<&str>, pl: Rc<RefCell<Player>>) {
        let pl = pl.borrow();
        if !self.is_host(pl.token) {
            pl.send_message("only chief sets points!");
            return;
        }

        if input.len() != 2 {
            pl.send_message("ya gotta set the new limit");
            return;
        }

        match input[1].to_string().parse::<u8>() {
            Ok(max) => {
                if max == 0 {
                    pl.send_message("bro dont make it 0 wtf man");
                    return;
                }
                self.max_points = max;
                pl.send_message(&format!("max points set to {}", self.max_points));
            }

            _ => pl.send_message(&"You have provided an invalid parameter."),
        }
    }

    pub fn send_message_from(&self, from: &Player, message: &str) {
        for pl in &self.list {
            pl.borrow().send_message_from(&from.name, &from.bg, &from.fg, message, from.level);
        }
    }

    pub fn thrustees(&mut self, input: Vec<&str>, pl: Rc<RefCell<Player>>) {
        let pl = pl.borrow();
        if !self.is_host(pl.token) {
            pl.send_message(
                "Only chief of the lobby is the only one who may set the THRUSTEE count.",
            );
            return;
        }

        if input.len() != 2 {
            pl.send_message(
                "A value must be provided to determine what the THRUSTEE count is to be.",
            );
            return;
        }

        match input[1].to_string().parse::<u8>() {
            Ok(max) => {
                if max < 2 {
                    pl.send_message(&format!("Brother, you must specify 2 or more for THRUSTEE count. This is so that we can guarantee some sort of picking decision for the THRUSTEE to partake in when selecting a desired THRUSTEE to use. Thank you for your understanding."));
                    return;
                }
                self.max_thrustee_choices = max;
                pl.send_message(&format!("max THRUSTEE set to {}", self.max_players));
            }

            _ => pl.send_message(&"Thou hast entered a value that we have deemed as unparsable for the requested THRUSTEE command that thou hast witch hath entered hitherto."),
        }
    }

    pub fn thrusters(&mut self, input: Vec<&str>, pl: Rc<RefCell<Player>>) {
        let pl = pl.borrow();
        if !self.is_host(pl.token) {
            pl.send_message("ONLY CHIEF CAN SET MAX THRUSTERS!!!");
            return;
        }

        if input.len() != 2 {
            pl.send_message("You need to give me a value man");
            return;
        }

        match input[1].to_string().parse::<u8>() {
            Ok(max) => {
                if max < 2 {
                    pl.send_message(&format!("bro u need at least two THRUSTERS, try again?"));
                    return;
                }

                self.hand_size = max;
                pl.send_message(&format!("max THRUSTERS set to {}", self.max_players));
            }

            _ => {
                pl.send_message(&"only positive numbers dude, please!!! (and not too big neither)")
            }
        }
    }

    pub fn thrust(&mut self, input: Vec<&str>, pl: Rc<RefCell<Player>>) {
        {
            let pl = pl.borrow();

            // Check if thrusted
            if self.game.thrusted_players.contains(&pl.token) {
                pl.send_message("You have already THRUSTED, you cannot THRUST again.");
                return;
            }

            // Check number of inputs
            if input.len() < 2 {
                pl.send_message(&"Index required!");
                return;
            }
        }

        // For handling mut borrow
        let resulting_thrust = {
            let mut pl = pl.borrow_mut();

            // Check correct # of thrusters
            let num_thrusters = input.len() as i32 - 1;
            let num_underscore = Deck::count_underscores(&self.game.current_thrustee);
            if num_thrusters != num_underscore {
                pl.send_message("bro that ain't the right number of THRUSTERS");
                return;
            }

            let mut resulting_thrust = self.game.current_thrustee.clone();
            let mut to_remove = HashSet::new();
            // Handle mutliple underscores
            for i in 1..input.len() {
                // Convert from 1-indexing to 0-indexing
                // Use i32 to account for underflow
                let index = match input[i].parse::<i32>() {
                    Ok(value) => value - 1,
                    Err(_) => {
                        pl.send_message("Yeah it looks like your THRUST didn't work. Index failed to be provided?");
                        return;
                    }
                };

                // Check if valid index
                if index >= pl.game.deck.thrusters.len() as i32 || index < 0 {
                    pl.send_message("That shit's out of bound bro");
                    return;
                }

                let picked_thruster = pl.game.deck.thrusters[index as usize].clone();
                to_remove.insert(picked_thruster.clone());
                // Surround with <u> to underline text
                let formatted_thruster = format!("<u>{}</u>", picked_thruster);
                resulting_thrust = Deck::thrust(&formatted_thruster, &resulting_thrust);
            }

            // Remove thrusted thrusters
            let mut updated_thrusters = Vec::new();
            for thruster in &pl.game.deck.thrusters {
                if !to_remove.contains(thruster) {
                    updated_thrusters.push(thruster.clone())
                }
            }
            pl.game.deck.thrusters = updated_thrusters;
            self.game.thrusted_players.push(pl.token.clone());

            // Handle picked
            self.game.current_thrusts.insert(
                self.game.current_thrusts.len(),
                (pl.token, resulting_thrust.clone()),
            );

            self.refill_remaining_thrusters(&mut pl);
            resulting_thrust
        };

        let mut messages = vec![format!(
            "{}. {}",
            // Use 1-indexing for showing result
            &self.game.current_thrusts.len(),
            &resulting_thrust
        )];

        // Check if everyone has thrusted
        let mut did_everyone_thrust = true;
        for (_, pl) in self.list.iter().enumerate() {
            let pl = pl.borrow();
            if pl.state != PlayerState::Deciding && !self.game.thrusted_players.contains(&pl.token)
            {
                did_everyone_thrust = false;
                break;
            }
        }
        if did_everyone_thrust {
            messages.push(String::from("<br/>Everyone has THRUSTED! By popular demand we are adding this message in to notify everyone that it's fine to choose a THRUST now. I didn't want it to have to come down to this, but I added it in due to pressure from our publishers."));
        }

        // Notify message
        self.send_messages(messages);
    }

    pub fn start(&mut self, pl: Rc<RefCell<Player>>) {
        {
            let pl = pl.borrow();

            if !self.is_host(pl.token) {
                pl.send_message(&format!("Only chief can start game!"));
                return;
            }
        }

        // Reset game settings
        self.game = LobbyGame::new();
        self.game.deck.clear();
        // Add in house cards to lobby deck if bool is true
        if self.house > 0 {
            let mut default_deck = Deck::default();
            default_deck.shuffle_deck();
            // Truncate to house limit
            default_deck.limit(self.house);
            self.game.deck = default_deck;
        }

        // Add each person's deck in
        {
            let decks: Vec<Deck> = self
                .list
                .iter()
                .map(|pl| pl.borrow().personal_deck.clone())
                .collect();
            for deck in decks {
                self.game.deck.thrustees.append(&mut deck.thrustees.clone());
                self.game.deck.thrusters.append(&mut deck.thrusters.clone());
            }
        }

        // Validate THRUSTEES (need 1 THRUSTEE)
        if self.game.deck.thrustees.is_empty() {
            pl.borrow().send_message("Dude, I can't start the game for you because yall don't got enough THRUSTEES. Here's a lil bit of mathematics:<br/>Total THRUSTEES HAS to BE GREATER THAN 0");
            return;
        }

        // Validate THRUSTERS (need 1 THRUSTER)
        if self.game.deck.thrusters.is_empty() {
            pl.borrow().send_message("Yo... got an issue boss, we don't go enough THRUSTERS. Let me calculate to tell you why:<br/>Total THRUSTERS HAS to BE GREATER THAN 0");
            return;
        }

        self.game.deck_reference = self.game.deck.clone();
        self.game.deck.shuffle_deck();
        self.state = LobbyState::Playing;
        self.refill_thrustees();

        // Elaborateness to call &mut self
        for i in 0..self.list.len() {
            let pl = self.list[i].clone();
            // While we're at it reset the player's game settings omegalul
            pl.borrow_mut().game = PlayerGame::new();
            self.refill_thrusters(&mut pl.borrow_mut());
        }

        let thrustee_name = self.list[self.game.thrustee].borrow().name.clone();
        for (i, pl) in self.list.iter().enumerate() {
            let mut pl = pl.borrow_mut();
            pl.state = PlayerState::Waiting;
            pl.up_games_played();

            if i == self.game.thrustee {
                pl.state = PlayerState::Choosing;
                let mut messages =
                    vec!["You are the THRUSTEE. Choose NOW..........<br/>".to_string()];
                messages.extend(self.print_thrustee_choices());
                pl.send_messages(&messages);
            } else {
                pl.send_message(&format!(
                    "You are a THRUSTER. waiting for a good THRUSTEE from {}; mmm baby!",
                    &thrustee_name
                ));
            }
        }
    }

    pub fn start_endless(&mut self) {
        self.state = LobbyState::Playing;
        self.game.deck = Deck::default();
        self.game.deck_reference = self.game.deck.clone();
        self.game.deck.shuffle_deck();
        self.refill_thrustees();
    }

    pub fn who(&self, pl: Rc<RefCell<Player>>) {
        let pl = pl.borrow();
        let token = &pl.token;
        let mut messages = Vec::new();

        for pl_rc in &self.list {
            let pl = pl_rc.borrow();
            let name = &pl.name;
            let level = &pl.level;

            let mut person = "";
            if token == &pl.token {
                person = " (You)";
            }

            let message = if self.is_host(pl.token) {
                format!("{} ({}): chief{}", name, level, person).to_string()
            } else {
                format!("{} ({}){}", name, level, person).to_string()
            };

            messages.push(message);
        }

        messages.sort_unstable_by(|a, b| a.cmp(&b));

        pl.send_messages(&messages);
    }

    pub fn who_in_game(&self, pl: Rc<RefCell<Player>>) {
        let pl = pl.borrow();
        let token = pl.token;
        let mut messages = Vec::new();
        for rc in &self.list {
            let player = rc.borrow();
            let you = if token == player.token {
                " (Yourself)"
            } else {
                ""
            };
            messages.push(format!(
                "{}/{} points: {}{}",
                player.game.points, self.max_points, player.name, you
            ));
        }

        // Sort the messages so that they are ordered by highest points
        messages.sort_unstable_by(|a, b| a.cmp(b).reverse());

        pl.send_messages(&messages);
    }
}