-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
995 lines (835 loc) · 35 KB
/
Copy pathMain.java
File metadata and controls
995 lines (835 loc) · 35 KB
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
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.io.Console;
import java.io.IOException;
class Node {
String data;
Node next;
Node(String data) {
this.data = data;
this.next = null;
}
}
class SinglyLinkedList {
Node head;
public void append(String data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) temp = temp.next;
temp.next = newNode;
}
}
public boolean isEmpty() {
return head == null;
}
public void sortByTitle() {
if (head == null || head.next == null) return;
boolean swapped;
do {
swapped = false;
Node curr = head;
while (curr.next != null) {
String title1 = curr.data.split(",")[0].toLowerCase();
String title2 = curr.next.data.split(",")[0].toLowerCase();
if (title1.compareTo(title2) > 0) {
String temp = curr.data;
curr.data = curr.next.data;
curr.next.data = temp;
swapped = true;
}
curr = curr.next;
}
} while (swapped);
}
public void printEvents() {
Node temp = head;
while (temp != null) {
String[] parts = temp.data.split(",");
if (parts.length >= 4) {
System.out.printf("• %-15s | %-10s | %-12s | Capacity: %s\n",
parts[0], parts[1], parts[2], parts[3]);
} else {
System.out.println("⚠️ Malformed event entry skipped: " + temp.data);
}
temp = temp.next;
}
}
// Optional: for file writing support
public List<String> toFileData() {
List<String> dataList = new ArrayList<>();
Node temp = head;
while (temp != null) {
dataList.add(temp.data);
temp = temp.next;
}
return dataList;
}
public boolean contains(String title) {
Node temp = head;
while (temp != null) {
String currentTitle = temp.data.split(",")[0].trim().toLowerCase();
if (currentTitle.equals(title.trim().toLowerCase())) {
return true;
}
temp = temp.next;
}
return false;
}
public void delete(String title) {
if (head == null) return;
String target = title.trim().toLowerCase();
Node temp = head, prev = null;
while (temp != null) {
String currentTitle = temp.data.split(",")[0].trim().toLowerCase();
if (currentTitle.equals(target)) {
if (prev == null) {
// Deleting head
head = temp.next;
} else {
prev.next = temp.next;
}
return;
}
prev = temp;
temp = temp.next;
}
}
}
public class Main {
private static final String EVENT_FILE = "events.txt";
private static final String USER_EVENT_FILE = "user_events.txt";
private static final String REG_FILE = "registrations.txt";
private static final String FEEDBACK_FILE = "feedback.txt";
private static final String USER_FILE = "users.txt";
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
introAnimation();
initFiles();
preloadUsers();
mainMenu();
}
SinglyLinkedList events = new SinglyLinkedList();
private static void introAnimation() {
clearConsole();
System.out.println("\n\n🎉 Welcome to");
slowPrint(" ████████╗████████╗ ███████╗ ████████╗██╗ ███████╗██╗ ██████╗ ██╗ ██╗\n");
slowPrint(" ██╔════╝ ██╔════╝ ██╔════╝ ╚══██╔══╝██║ ██╔════╝██║ ██╔═══██╗ ██║ ██║\n");
slowPrint(" █████╗ █████╗ ███████╗ ██║ ██║ █████╗ ██║ ██║ ██║ ██║ █╗ ██║\n");
slowPrint(" ██╔══╝ ██╔══╝ ╚════██║ ██║ ██║ ██╔══╝ ██║ ██║ ██║ ██║███╗██║\n");
slowPrint(" ██║ ███████╗ ███████║ ██║ ██║ ██╗ ███████╗╚██████╔╝ ╚███╔███╔╝\n");
slowPrint(" ╚═╝ ╚══════╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═════╝ ╚══╝╚══╝\n");
loadingDots("Loading FestiFlow");
}
private static void slowPrint(String text) {
for (char ch : text.toCharArray()) {
System.out.print(ch);
try {
Thread.sleep(5); // adjust speed here
} catch (InterruptedException ignored) {}
}
}
private static void loadingDots(String message) {
System.out.print("\n" + message);
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(500); // dot interval
System.out.print(".");
} catch (InterruptedException ignored) {}
}
System.out.println("\n");
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {}
}
private static void clearConsole() {
try {
if (System.getProperty("os.name").contains("Windows")) {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
} else {
System.out.print("\033[H\033[2J");
System.out.flush();
}
} catch (Exception e) {
// Fallback in case of an error
System.out.println("\n\n");
}
}
private static void initFiles() {
createIfNotExists(EVENT_FILE);
createIfNotExists(USER_EVENT_FILE);
createIfNotExists(REG_FILE);
createIfNotExists(FEEDBACK_FILE);
createIfNotExists(USER_FILE);
}
private static void createIfNotExists(String filename) {
try {
File file = new File(filename);
if (!file.exists()) file.createNewFile();
} catch (IOException e) {
System.out.println("Error initializing file: " + filename);
}
}
private static void mainMenu() {
while (true) {
System.out.println("\n=== 🎉 Welcome to FestiFlow ===");
System.out.println("1. Login");
System.out.println("2. Register");
System.out.println("3. Change Password");
System.out.println("4. Exit");
System.out.print("Choose an option: ");
int option = getIntInput(1, 4);
switch (option) {
case 1 -> login();
case 2 -> registerUser();
case 3 -> changePassword();
case 4 -> {
System.out.println("👋 Goodbye!");
return;
}
}
}
}
private static void login() {
System.out.print("Username: ");
String username = scanner.nextLine();
String password = readPassword("Password: ");
String role = authenticateUser(username, password);
if (role == null) {
System.out.println("❌ Invalid credentials.");
return;
}
if (role.equals("admin")) adminMenu();
else userMenu(username);
}
private static void registerUser() {
System.out.print("Choose a username: ");
String username = scanner.nextLine();
if (!isValidUsername(username)) {
System.out.println("❌ Username must be more than 5 characters.");
return;
}
if (userExists(username)) {
System.out.println("⚠️ Username already taken.");
return;
}
String password = readPassword("Choose a password: ");
if (!isValidPassword(password)) {
System.out.println("❌ Password must be more than 8 characters and include a number and a special character.");
return;
}
System.out.print("Enter your email: ");
String email = scanner.nextLine();
if (!isValidEmail(email)) {
System.out.println("❌ Invalid email format. Use @gmail.com, @yahoo.com, or @chitkara.edu.in.");
return;
}
if (isChitkaraEmail(email)) {
appendToFile(USER_FILE, username + "," + password + ",user");
System.out.println("✅ Registration successful!");
} else {
appendToFile("pending_users.txt", username + "," + password + "," + email);
System.out.println("📝 Registration request sent for admin approval.");
}
}
private static boolean isValidUsername(String username) {
return username != null && username.length() > 5;
}
private static boolean isValidPassword(String password) {
if (password.length() <= 8) return false;
boolean hasNumber = false;
boolean hasSpecial = false;
for (char c : password.toCharArray()) {
if (Character.isDigit(c)) hasNumber = true;
if (!Character.isLetterOrDigit(c)) hasSpecial = true;
}
return hasNumber && hasSpecial;
}
private static boolean isValidEmail(String email) {
return email != null && (
email.endsWith("@gmail.com") ||
email.endsWith("@yahoo.com") ||
email.endsWith("@chitkara.edu.in")
);
}
private static boolean isChitkaraEmail(String email) {
return email != null && email.endsWith("@chitkara.edu.in");
}
private static void changePassword() {
System.out.print("Username: ");
String username = scanner.nextLine();
String oldPassword = readPassword("Old Password: ");
if (!userExists(username, oldPassword)) {
System.out.println("❌ Invalid credentials.");
return;
}
String newPassword = readPassword("New Password: ");
List<String> users = readFile(USER_FILE);
List<String> updated = new ArrayList<>();
for (String user : users) {
String[] parts = user.split(",");
if (parts[0].equals(username)) {
updated.add(parts[0] + "," + newPassword + "," + parts[2]);
} else {
updated.add(user);
}
}
overwriteFile(USER_FILE, updated);
System.out.println("🔁 Password changed successfully!");
}
private static void adminMenu() {
while (true) {
System.out.println("\n=== 🛠️ ADMIN MENU ===");
System.out.println("1. Create Event");
System.out.println("2. View Events");
System.out.println("3. Edit Event");
System.out.println("4. Delete Event");
System.out.println("5. View Registrations");
System.out.println("6. View Feedback");
System.out.println("7. View User-Proposed Events");
System.out.println("8. Search Events");
System.out.println("9. Dashboard Summary");
System.out.println("10. Review Pending Users"); // <-- new option
System.out.println("11. Logout");
System.out.print("Choose an option: ");
int choice = getIntInput(1, 11);
switch (choice) {
case 1 -> createEvent();
case 2 -> viewEvents(EVENT_FILE);
case 3 -> editEvent();
case 4 -> deleteEvent();
case 5 -> viewFile(REG_FILE, "Registrations");
case 6 -> viewFile(FEEDBACK_FILE, "Feedback");
case 7 -> approveOrRejectProposals();
case 8 -> searchEvents();
case 9 -> showAdminDashboard();
case 10 -> processPendingUsers(); // <-- handle pending user registrations
case 11 -> {
System.out.println("👋 Logged out.");
return;
}
}
}
}
private static void userMenu(String username) {
while (true) {
System.out.println("\n=== 👤 USER MENU ===");
System.out.println("1. View Events");
System.out.println("2. Register for Event");
System.out.println("3. Give Feedback");
System.out.println("4. Propose an Event");
System.out.println("5. My Participation");
System.out.println("6. Search Events");
System.out.println("7. Logout");
System.out.print("Choose an option: ");
int choice = getIntInput(1, 7);
switch (choice) {
case 1 -> viewEvents(EVENT_FILE);
case 2 -> registerForEvent(username);
case 3 -> giveFeedback(username);
case 4 -> proposeEvent(username);
case 5 -> viewUserParticipation(username);
case 6 -> searchEvents();
case 7 -> {
System.out.println("👋 Logged out.");
return;
}
}
}
}
private static void createEvent() {
SinglyLinkedList eventList = new SinglyLinkedList();
// Collect event data
System.out.print("Event Title: ");
String title = scanner.nextLine(); // Title remains case-sensitive
System.out.print("Location: ");
String location = scanner.nextLine();
// Date input with format validation
LocalDate date;
while (true) {
System.out.print("Date (yyyy-mm-dd): ");
try {
date = LocalDate.parse(scanner.nextLine()); // Ensures the date format is yyyy-mm-dd
break;
} catch (DateTimeParseException e) {
System.out.println("⚠️ Invalid date format. Please use yyyy-mm-dd.");
}
}
// Capacity input with number-only validation
int capacity;
while (true) {
System.out.print("Max Capacity: ");
try {
capacity = Integer.parseInt(scanner.nextLine());
if (capacity > 0) {
break; // Ensure capacity is a positive number
} else {
System.out.println("⚠️ Capacity must be greater than 0.");
}
} catch (NumberFormatException e) {
System.out.println("⚠️ Invalid input. Please enter a valid number for capacity.");
}
}
// Combine event data into a string format
String eventData = title + "," + location + "," + date + "," + capacity;
// Append event to linked list
eventList.append(eventData);
// Write event to file
appendToFile(EVENT_FILE, eventData);
System.out.println("✅ Event created successfully.");
}
private static void viewFile(String filename, String title) {
System.out.println("\n=== 📄 " + title + " ===");
List<String> lines = readFile(filename);
if (lines.isEmpty()) {
System.out.println("No " + title.toLowerCase() + " found.");
return;
}
for (String line : lines) {
System.out.println("- " + line);
}
}
private static void registerForEvent(String username) {
SinglyLinkedList eventList = new SinglyLinkedList();
// Load events from file into linked list
List<String> events = readFile(EVENT_FILE);
if (events.isEmpty()) {
System.out.println("⚠️ No events available.");
return;
}
// Add events to the SinglyLinkedList
for (String event : events) {
eventList.append(event); // ✅ Correct method from your class
// assuming `add()` adds to the list
}
// View events from linked list
eventList.printEvents();
// User selects an event to register for
System.out.print("Enter event title to register: ");
String title = scanner.nextLine();
if (!eventList.contains(title)) {
System.out.println("⚠️ Event not found.");
return;
}
// Check if the user is already registered for the event
boolean alreadyRegistered = readFile(REG_FILE).stream()
.anyMatch(reg -> reg.equalsIgnoreCase(title + "," + username));
if (alreadyRegistered) {
System.out.println("⚠️ Already registered.");
return;
}
// Register user by appending to the registration file
appendToFile(REG_FILE, title + "," + username);
System.out.println("✅ Registered for event.");
}
private static void giveFeedback(String username) {
System.out.print("Enter event name: ");
String title = scanner.nextLine();
System.out.print("Your feedback: ");
String feedback = scanner.nextLine();
System.out.print("Rate the event (1–5): ");
int rating = getIntInput(1, 5);
appendToFile(FEEDBACK_FILE, title + "," + username + "," + rating + "," + feedback);
System.out.println("🙏 Thanks for your feedback!");
}
private static void processPendingUsers() {
List<String> pending = readFile("pending_users.txt");
if (pending.isEmpty()) {
System.out.println("\n📭 No pending user registrations.");
return;
}
System.out.println("\n📥 Total pending requests: " + pending.size());
System.out.print("Do you want to view and process them? (yes/no): ");
String viewChoice = scanner.nextLine().trim().toLowerCase();
if (!viewChoice.equals("yes")) {
System.out.println("⏳ Skipping review for now.");
return;
}
System.out.println("\n=== 🕵️ Review Pending Users ===");
for (int i = 0; i < pending.size(); i++) {
String[] parts = pending.get(i).split(",");
if (parts.length < 3) continue;
String uname = parts[0], email = parts[2];
System.out.printf("%d. Username: %s, Email: %s\n", i + 1, uname, email);
}
List<String> updatedPending = new ArrayList<>();
while (true) {
System.out.print("Enter the number of the user to process (0 to finish): ");
String input = scanner.nextLine().trim();
int choice;
try {
choice = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("⚠️ Please enter a valid number.");
continue;
}
if (choice == 0) break;
if (choice < 1 || choice > pending.size()) {
System.out.println("⚠️ Invalid number. Try again.");
continue;
}
String request = pending.get(choice - 1);
if (request == null) {
System.out.println("⚠️ Already processed.");
continue;
}
String[] parts = request.split(",");
if (parts.length < 3) {
System.out.println("⚠️ Malformed request. Skipping.");
continue;
}
String uname = parts[0];
String pwd = parts[1];
String email = parts[2];
System.out.print("Approve or Reject this user? (a/r): ");
String decision = scanner.nextLine().trim().toLowerCase();
if (decision.equals("a")) {
appendToFile(USER_FILE, uname + "," + pwd + ",user");
System.out.println("✅ User " + uname + " approved and registered.");
} else if (decision.equals("r")) {
appendToFile("rejected_users.txt", uname + "," + email);
System.out.println("❌ User " + uname + " rejected and logged.");
} else {
System.out.println("⚠️ Invalid choice. Skipping this request.");
updatedPending.add(request);
continue;
}
// Mark as processed
pending.set(choice - 1, null);
}
// Save remaining unprocessed requests
for (String req : pending) {
if (req != null) updatedPending.add(req);
}
overwriteFile("pending_users.txt", updatedPending);
System.out.println("📁 Pending requests updated.");
}
private static void proposeEvent(String username) {
String title, description, location, date;
int capacity;
System.out.print("Event Title: ");
title = scanner.nextLine();
System.out.print("Description: ");
description = scanner.nextLine();
System.out.print("Location: ");
location = scanner.nextLine();
// Validate date format
while (true) {
System.out.print("Date (yyyy-mm-dd): ");
date = scanner.nextLine();
if (date.matches("\\d{4}-\\d{2}-\\d{2}")) {
break;
} else {
System.out.println("❌ Invalid date format. Please use yyyy-mm-dd.");
}
}
// Validate capacity is a number
while (true) {
System.out.print("Capacity: ");
String capInput = scanner.nextLine();
try {
capacity = Integer.parseInt(capInput);
if (capacity <= 0) {
System.out.println("❌ Capacity must be greater than 0.");
} else {
break;
}
} catch (NumberFormatException e) {
System.out.println("❌ Invalid input. Please enter a numeric value for capacity.");
}
}
// Saving format: title,description,location,date,capacity,username
appendToFile(USER_EVENT_FILE, title + "," + description + "," + location + "," + date + "," + capacity + "," + username);
System.out.println("✅ Proposal submitted. Awaiting admin approval.");
}
private static void approveOrRejectProposals() {
final String REJECTED_EVENTS_FILE = "rejected_events.txt";
LinkedList<String> proposals = new LinkedList<>(readFile(USER_EVENT_FILE));
if (proposals.isEmpty()) {
System.out.println("⚠️ No pending proposals.");
return;
}
System.out.println("📋 You have " + proposals.size() + " pending event proposals.");
System.out.print("Do you want to view them? (y/n): ");
String viewChoice = scanner.nextLine();
if (!viewChoice.equalsIgnoreCase("y")) {
System.out.println("Returning to admin menu...");
return;
}
// Display all proposals with index numbers
for (int i = 0; i < proposals.size(); i++) {
String[] parts = proposals.get(i).split(",", 6);
if (parts.length < 6) continue;
System.out.println("\n[" + (i + 1) + "] Proposal by " + parts[5]);
System.out.println("Title: " + parts[0]);
System.out.println("Description: " + parts[1]);
System.out.println("Location: " + parts[2]);
System.out.println("Date: " + parts[3]);
System.out.println("Capacity: " + parts[4]);
}
LinkedList<String> approved = new LinkedList<>();
while (true) {
System.out.print("\nEnter the proposal number to review (0 to exit): ");
String input = scanner.nextLine();
if (input.equals("0")) break;
try {
int index = Integer.parseInt(input) - 1;
if (index < 0 || index >= proposals.size()) {
System.out.println("❌ Invalid proposal number.");
continue;
}
String[] parts = proposals.get(index).split(",", 6);
String title = parts[0];
String description = parts[1];
String location = parts[2];
String date = parts[3];
String capacity = parts[4];
String username = parts[5];
System.out.println("\n📌 Proposal by " + username);
System.out.println("Title: " + title);
System.out.println("Description: " + description);
System.out.println("Location: " + location);
System.out.println("Date: " + date);
System.out.println("Capacity: " + capacity);
System.out.print("Approve this proposal? (y/n): ");
String decision = scanner.nextLine();
if (decision.equalsIgnoreCase("y")) {
approved.add(String.join(",", title, location, date, capacity));
proposals.remove(index);
System.out.println("✅ Approved.");
} else {
// Save rejected event to rejected_events.txt
String rejectedEvent = String.join(",", title, description, location, date, capacity, username);
appendToFile(REJECTED_EVENTS_FILE, rejectedEvent);
proposals.remove(index);
System.out.println("❌ Rejected and saved to " + REJECTED_EVENTS_FILE);
}
} catch (NumberFormatException e) {
System.out.println("❌ Please enter a valid number.");
}
}
overwriteFile(USER_EVENT_FILE, proposals);
approved.forEach(e -> appendToFile(EVENT_FILE, e));
}
private static void editEvent() {
LinkedList<String> events = new LinkedList<>(readFile(EVENT_FILE));
if (events.isEmpty()) {
System.out.println("⚠️ No events to edit.");
return;
}
viewEvents(EVENT_FILE);
System.out.print("Enter title of event to edit: ");
String title = scanner.nextLine();
LinkedList<String> updated = new LinkedList<>();
boolean found = false;
for (String event : events) {
String[] parts = event.split(",");
if (parts.length < 4) {
updated.add(event); // Keep malformed lines unchanged
continue;
}
if (parts[0].equalsIgnoreCase(title)) {
found = true;
System.out.print("New Location: ");
String newLoc = scanner.nextLine();
// Date validation
LocalDate newDate;
while (true) {
System.out.print("New Date (yyyy-mm-dd): ");
try {
newDate = LocalDate.parse(scanner.nextLine());
break;
} catch (DateTimeParseException e) {
System.out.println("⚠️ Invalid date format. Please use yyyy-mm-dd.");
}
}
// Capacity validation
int newCap;
while (true) {
System.out.print("New Capacity: ");
try {
newCap = Integer.parseInt(scanner.nextLine());
if (newCap > 0) break;
else System.out.println("⚠️ Capacity must be greater than 0.");
} catch (NumberFormatException e) {
System.out.println("⚠️ Invalid input. Please enter a number.");
}
}
updated.add(parts[0] + "," + newLoc + "," + newDate + "," + newCap);
} else {
updated.add(event); // Keep unchanged events
}
}
if (!found) {
System.out.println("⚠️ Event not found.");
return;
}
overwriteFile(EVENT_FILE, updated);
System.out.println("✅ Event updated.");
}
private static void deleteEvent() {
SinglyLinkedList eventList = new SinglyLinkedList();
// Load events from file into linked list
LinkedList<String> events = new LinkedList<>(readFile(EVENT_FILE));
if (events.isEmpty()) {
System.out.println("⚠️ No events available.");
return;
}
// Add events from file into the linked list
for (String eventData : events) {
eventList.append(eventData);
}
// Display events for deletion
eventList.printEvents();
// User selects an event to delete
System.out.print("Enter event title to delete: ");
String title = scanner.nextLine();
// Check if the event exists
if (!eventList.contains(title)) {
System.out.println("⚠️ Event not found.");
return;
}
// Delete the event from the linked list
eventList.delete(title);
// Overwrite event file with updated event list
overwriteFile(EVENT_FILE, eventList.toFileData());
System.out.println("🗑️ Event deleted.");
}
private static void viewEvents(String file) {
List<String> fileData = readFile(file);
SinglyLinkedList events = new SinglyLinkedList();
for (String line : fileData) {
events.append(line);
}
if (events.isEmpty()) {
System.out.println("⚠️ No events to display.");
return;
}
// Sort events by title
events.sortByTitle();
// Display events
System.out.println("\n=== 📅 Upcoming Events ===");
events.printEvents();
}
private static void searchEvents() {
System.out.print("Search by (title/location): ");
String term = scanner.nextLine().toLowerCase();
LinkedList<String> events = new LinkedList<>(readFile(EVENT_FILE));
boolean found = false;
for (String e : events) {
if (e.toLowerCase().contains(term)) {
System.out.println("🔍 " + e);
found = true;
}
}
if (!found) System.out.println("❌ No matching events found.");
}
private static void viewUserParticipation(String username) {
System.out.println("\n=== 👤 Your Event Registrations ===");
List<String> registrations = readFile(REG_FILE);
boolean found = false;
for (String reg : registrations) {
String[] parts = reg.split(",");
if (parts.length >= 2 && parts[1].equalsIgnoreCase(username)) {
System.out.println("- Registered for event: " + parts[0]);
found = true;
}
}
if (!found) {
System.out.println("⚠️ No registrations found.");
}
}
private static void submitFeedback(String username) {
System.out.print("Enter your feedback: ");
String feedback = scanner.nextLine().trim();
if (!feedback.isEmpty()) {
appendToFile(FEEDBACK_FILE, username + "," + feedback);
System.out.println("✅ Feedback submitted. Thank you!");
} else {
System.out.println("❗ Feedback cannot be empty.");
}
}
private static void viewAllFeedbacks() {
System.out.println("\n=== 💬 All Feedbacks ===");
List<String> feedbacks = readFile(FEEDBACK_FILE);
if (feedbacks.isEmpty()) {
System.out.println("No feedbacks found.");
return;
}
for (String fb : feedbacks) {
String[] parts = fb.split(",", 2);
if (parts.length == 2) {
System.out.println(parts[0] + ": " + parts[1]);
}
}
}
private static void showAdminDashboard() {
System.out.println("\n=== 📊 Dashboard ===");
System.out.println("Total Users: " + readFile(USER_FILE).size());
System.out.println("Total Events: " + readFile(EVENT_FILE).size());
System.out.println("Total Registrations: " + readFile(REG_FILE).size());
System.out.println("Total Feedbacks: " + readFile(FEEDBACK_FILE).size());
}
private static void preloadUsers() {
if (readFile(USER_FILE).isEmpty()) {
appendToFile(USER_FILE, "admin,admin,admin");
}
}
private static String authenticateUser(String username, String password) {
for (String line : readFile(USER_FILE)) {
String[] parts = line.split(",");
if (parts[0].equals(username) && parts[1].equals(password)) {
return parts[2];
}
}
return null;
}
private static boolean userExists(String username) {
return readFile(USER_FILE).stream()
.anyMatch(line -> line.split(",")[0].equals(username));
}
private static boolean userExists(String username, String password) {
return authenticateUser(username, password) != null;
}
private static List<String> readFile(String filename) {
try {
return Files.readAllLines(Paths.get(filename));
} catch (IOException e) {
return new ArrayList<>();
}
}
private static void appendToFile(String filename, String data) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename, true))) {
bw.write(data);
bw.newLine();
} catch (IOException e) {
System.out.println("Error writing to file: " + filename);
}
}
private static void overwriteFile(String filename, List<String> lines) {
try {
Files.write(Paths.get(filename), lines, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException e) {
System.out.println("Error overwriting file: " + filename);
}
}
private static int getIntInput(int min, int max) {
while (true) {
try {
int value = Integer.parseInt(scanner.nextLine());
if (value >= min && value <= max) return value;
} catch (NumberFormatException ignored) {}
System.out.print("❗ Invalid input. Enter a number between " + min + " and " + max + ": ");
}
}
private static String readPassword(String prompt) {
System.out.print(prompt);
return scanner.nextLine();
}
}