-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
879 lines (767 loc) · 27.8 KB
/
Program.cs
File metadata and controls
879 lines (767 loc) · 27.8 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
using SDP_Project;
using System.ComponentModel.DataAnnotations;
var grabberoo = new Grabberoo();
var restaurants = new List<Restaurant>([
CreateItalianRestaurant(),
CreateChineseRestaurant(),
CreateFastFoodRestaurant()
]);
while (true)
{
Console.WriteLine("\n===== Welcome to Grabberoo =====");
Console.WriteLine("1. Place a new order");
Console.WriteLine("2. View favourite orders");
Console.WriteLine("3. Exit");
int mainChoice = GetIntInput("Select an option (1-3): ", 1, 3);
if (mainChoice == 1)
{
PlaceOrder(restaurants, grabberoo);
}
else if (mainChoice == 2)
{
ViewFavouriteOrders(grabberoo, restaurants);
}
else if (mainChoice == 3)
{
Console.WriteLine("Thank you for using Grabberoo!");
break;
}
}
/****** Menu creation ******/
static Menu CreateItalianMenu()
{
var pastaMenu = new Menu("Pasta");
pastaMenu.Add(new Pasta
{
Name = "Spaghetti Carbonara",
Description = "Yummy carbonara.",
BasePrice = 10.0,
PastaType = "spaghetti",
SauceType = "creamy"
});
pastaMenu.Add(new Pasta
{
Name = "Penne Arrabbiata",
Description = "Penne with spicy arrabbiata sauce.",
BasePrice = 11.0,
PastaType = "penne",
SauceType = "spicy tomato"
});
pastaMenu.Add(new Pasta
{
Name = "Fettuccine Alfredo",
Description = "Fettuccine with creamy alfredo sauce.",
BasePrice = 12.0,
PastaType = "fettuccine",
SauceType = "creamy",
Discount = 2.0
});
var pizzaMenu = new Menu("Pizza");
pizzaMenu.Add(new Pizza
{
Name = "Hawaiian Pizza",
Description = "Hawaiian Pizza with thin crust and tomato sauce",
BasePrice = 11.0,
Crust = "thin",
SauceType = "tomato"
});
pizzaMenu.Add(new Pizza
{
Name = "Pepperoni Pizza",
Description = "Pepperoni Pizza with thick crust and tomato sauce",
BasePrice = 11.0,
Crust = "thick",
SauceType = "tomato"
});
pizzaMenu.Add(new Pizza
{
Name = "Durian Pizza",
Description = "Delicious Durian Pizza with thick crust and durian sauce",
BasePrice = 15.0,
Crust = "thick",
SauceType = "durian"
});
return new Menu("Italian") { Components = [pastaMenu, pizzaMenu] };
}
static Menu CreateChineseMenu()
{
var riceMenu = new Menu("Rice");
riceMenu.Add(new FriedRice
{
Name = "Egg Fried Rice",
Description = "Fried Rice with Egg",
BasePrice = 8.99,
CookingStyle = "Wok Hei",
SpiceLevel = 3
});
riceMenu.Add(new FriedRice
{
Name = "Chilli Crab Egg Fried Rice",
Description = "Fried Rice with Chilli Crab and Egg",
BasePrice = 20.0,
CookingStyle = "Wok Hei",
SpiceLevel = 4
});
var noodleMenu = new Menu("Noodle");
noodleMenu.Add(new BeeHoon
{
Name = "Fried Bee Hoon",
Description = "Fried Bee Hoon Noodle",
BasePrice = 7.0,
CookingStyle = "Wok-Hei",
SpiceLevel = 1
});
noodleMenu.Add(new BeeHoon
{
Name = "Seafood Bee Hoon",
Description = "Bee Hoon noodle with different types of seafood such as crab, lobster, stingray etc",
BasePrice = 15.0,
CookingStyle = "Wok-Hei",
SpiceLevel = 2
});
noodleMenu.Add(new BeeHoon
{
Name = "Curry Bee Hoon",
Description = "Bee Hoon noodle with curry sauce",
BasePrice = 6.0,
CookingStyle = "steamed",
SpiceLevel = 1
});
return new Menu("Chinese") { Components = [riceMenu, noodleMenu] };
}
static Menu CreateFastFoodMenu()
{
var burgerMenu = new Menu("Burger");
burgerMenu.Add(new Burger
{
Name = "Hamburger",
Description = "Hamburger with beef",
BasePrice = 8.0,
HasFrenchFries = false,
Drink = false
});
burgerMenu.Add(new Burger
{
Name = "Chilli Crab Burger",
Description = "Chilli Crab Burger Meal with Fries and Drinks",
BasePrice = 10.0,
HasFrenchFries = true,
Drink = true
});
var sandwichMenu = new Menu("Sandwich");
sandwichMenu.Add(new Sandwich
{
Name = "Ham Sandwich",
Description = "Ham Sandwich Alacarte",
BasePrice = 5.0,
Drink = false
});
sandwichMenu.Add(new Sandwich
{
Name = "Smoke Duck Sandwich Meal",
Description = "Smoke Duck Sandwich Meal with drink",
BasePrice = 8.0,
Drink = true
});
return new Menu("Fast food") { Components = [burgerMenu, sandwichMenu] };
}
/****** Restaurant creation ******/
static ItalianRestaurant CreateItalianRestaurant()
{
return new ItalianRestaurant
{
Name = "Bella Italia",
Address = "123 Italian Street",
Menu = CreateItalianMenu(),
StoreWideDiscount = 15.0, // 15% discount
DiscountDescription = "Italian Week Special! 15% off all orders!"
};
}
static ChineseRestaurant CreateChineseRestaurant()
{
return new ChineseRestaurant
{
Name = "Golden Dragon",
Address = "456 China Town",
Menu = CreateChineseMenu(),
StoreWideDiscount = 10.0, // 10% discount
DiscountDescription = "Chinese New Year Celebration! 10% off all orders!"
};
}
static FastFoodRestaurant CreateFastFoodRestaurant()
{
return new FastFoodRestaurant
{
Name = "Quick Bite",
Address = "789 Fast Lane",
Menu = CreateFastFoodMenu(),
StoreWideDiscount = 20.0, // 20% discount
DiscountDescription = "Weekend Madness! 20% off all orders!"
};
}
/****** Order placing ******/
static void PlaceOrder(List<Restaurant> restaurants, Grabberoo grabberoo)
{
// Allow the user to select a restaurant
Console.WriteLine("\nPlease select a restaurant:");
for (var i = 0; i < restaurants.Count; i++)
{
Console.WriteLine($"{i + 1}. {restaurants[i].Name}");
}
var restaurantChoice = GetIntInput($"Enter choice (1-{restaurants.Count}): ", 1, restaurants.Count);
var selectedRestaurant = restaurants[restaurantChoice - 1];
// Display the restaurant's menu, including special offers
Console.WriteLine($"\n--- Menu for {selectedRestaurant.Name} ---");
// Display restaurant discount information if available
if (selectedRestaurant.StoreWideDiscount > 0)
{
Console.WriteLine($"SPECIAL OFFER: {selectedRestaurant.DiscountDescription}");
}
PrintMenu(selectedRestaurant.Menu);
var itemCount = selectedRestaurant.Menu.ItemCount;
var orderItems = new List<OrderItem>();
while (true)
{
var itemChoice = GetIntInput($"\nSelect an item by number (1-{itemCount}): ", 1, itemCount);
var menuItem = selectedRestaurant.Menu.GetItem(itemChoice - 1);
var orderItem = ApplyDecoratorsToItem(new BasicOrderItem { MenuItem = menuItem });
orderItem.Quantity = GetIntInput("Enter quantity: ", 1, 100);
orderItems.Add(orderItem);
if (!GetYesNoInput("Add another item? (Y/N): ")) break;
}
Console.WriteLine("\nChoose order type:");
Console.WriteLine("1. Standard Delivery");
Console.WriteLine("2. Express Delivery");
int orderType = GetIntInput("Enter choice (1-2): ", 1, 2);
// Collect address and time
var deliveryAddress = GetStringInput("Enter delivery address: ");
DateTime deliveryTime;
do
{
string dtStr = GetStringInput("Enter delivery time (yyyy-MM-dd HH:mm): ");
if (!DateTime.TryParse(dtStr, out deliveryTime))
Console.WriteLine("Invalid date/time format. Try again.");
} while (deliveryTime < DateTime.Now);
// Calculate amount
double amount = 0;
foreach (var item in orderItems)
amount += item.Cost;
// Create order, set initial state and strategy
var order = new Order
{
Id = Guid.NewGuid().ToString(),
DeliveryAddress = deliveryAddress,
DeliveryTime = deliveryTime,
Amount = amount,
PaymentStrategy = new CashOnDelivery(), // Temporary, will be replaced after price breakdown
OrderItems = orderItems
};
// Store original amount before restaurant discount
double originalAmount = orderItems.Sum(item => item.Cost);
// Set the restaurant and recalculate total with discounts
order.SetRestaurant(selectedRestaurant);
// Create the OrderProcessor
OrderProcessor orderProcessor;
if (orderType == 1)
orderProcessor = new StandardOrderProcessor(order, selectedRestaurant);
else
orderProcessor = new ExpressOrderProcessor(order, selectedRestaurant);
// Process order and show total price
orderProcessor.ProcessOrder();
double restaurantDeliveryPrice = selectedRestaurant.RestaurantDeliveryPrice;
double processorFee = 0;
if (orderProcessor is StandardOrderProcessor sop)
processorFee = sop.DeliveryFee;
else if (orderProcessor is ExpressOrderProcessor eop)
processorFee = eop.ExpressCharge;
double combinedDeliveryPrice = restaurantDeliveryPrice + processorFee;
double totalPrice = orderProcessor.CalculatePrice();
// Set the total price for payment processing
order.TotalPrice = totalPrice;
// Display order summary
Console.WriteLine("\nOrder Summary:");
foreach (var item in orderItems)
{
Console.WriteLine($"- {item.Name} x{item.Quantity} ({item.Cost:C})");
}
Console.WriteLine($"Subtotal: {originalAmount:C}");
if (selectedRestaurant.StoreWideDiscount > 0)
{
double storeDiscountAmount = originalAmount - order.Amount;
Console.WriteLine($"Restaurant Discount ({selectedRestaurant.StoreWideDiscount}%): -{storeDiscountAmount:C}");
}
Console.WriteLine($"Delivery fee: {combinedDeliveryPrice:C}");
Console.WriteLine($"Grand total: {totalPrice:C}");
if (selectedRestaurant.StoreWideDiscount > 0)
{
double savings = originalAmount - order.Amount;
Console.WriteLine($"\nYou saved {savings:C} with the restaurant discount!");
}
Console.WriteLine("\nSelect payment method:");
Console.WriteLine("1. Credit Card");
Console.WriteLine("2. PayPal");
Console.WriteLine("3. Cash On Delivery");
int paymentChoice = GetIntInput("Enter choice (1-3): ", 1, 3);
PaymentStrategy paymentStrategy;
if (paymentChoice == 1)
{
string cardNumber;
do
{
cardNumber = GetStringInput("Enter card number (12-19 digits): ");
if (string.IsNullOrWhiteSpace(cardNumber) || cardNumber.Length < 12 || cardNumber.Length > 19 || !IsAllDigits(cardNumber))
Console.WriteLine("Invalid card number. Must be 12-19 digits.");
else break;
} while (true);
string expiryDate;
do
{
expiryDate = GetStringInput("Enter expiry date (MM/YY): ");
if (!IsValidExpiryDate(expiryDate))
Console.WriteLine("Invalid date. Please enter a valid expiry date in MM/YY format, not expired.");
else break;
} while (true);
string cvv;
do
{
cvv = GetStringInput("Enter CVV (3-4 digits): ");
if (string.IsNullOrWhiteSpace(cvv) || cvv.Length < 3 || cvv.Length > 4 || !IsAllDigits(cvv))
Console.WriteLine("Invalid CVV. Must be 3-4 digits.");
else break;
} while (true);
paymentStrategy = new CreditCardPayment
{
CardNumber = cardNumber,
ExpiryDate = expiryDate,
CVV = cvv
};
}
else if (paymentChoice == 2)
{
string email;
do
{
email = GetStringInput("Enter PayPal Email: ");
if (!IsValidEmail(email))
Console.WriteLine("Invalid email format. Try again.");
} while (!IsValidEmail(email));
string password = GetStringInput("Enter PayPal Password: ");
paymentStrategy = new PayPalPayment { Email = email, Password = password };
}
else // Cash On Delivery
{
Console.WriteLine("Cash On Delivery selected.");
paymentStrategy = new CashOnDelivery();
}
// Set the correct payment strategy after collecting payment details
order.PaymentStrategy = paymentStrategy;
// State-driven workflow
while (order.State != null)
{
// Show available actions based on current state
order.Submit();
if (order.State is PendingPaymentState)
{
Console.WriteLine("1. Pay");
Console.WriteLine("2. Cancel");
int choice = GetIntInput("Choose action: ", 1, 2);
if (choice == 1)
{
order.Pay();
Console.WriteLine("Processing payment...");
Console.WriteLine("Press 1 to Cancel, or wait 5 seconds for restaurant response...");
Console.WriteLine("1. Cancel");
DateTime endTime = DateTime.Now.AddSeconds(5);
bool cancelled = false;
while (DateTime.Now < endTime)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
if (key.KeyChar == '1')
{
order.Cancel();
cancelled = true;
break;
}
}
Thread.Sleep(100);
}
if (!cancelled)
{
// Simulate restaurant decision: 80% confirm, 20% reject
var rand = new Random();
int outcome = rand.Next(1, 101); // 1 to 100
if (outcome <= 80)
{
Console.WriteLine("Restaurant has CONFIRMED your order.");
order.Confirm();
}
else
{
Console.WriteLine("Restaurant has REJECTED your order.");
order.Reject();
break;
}
}
else
{
break;
}
}
else order.Cancel();
if (order.State == null) break;
}
else if (order.State is PendingConfirmationState)
{
// If order is still active, allow user to cancel
if (order.State != null)
{
if (GetYesNoInput("Would you like to cancel your order? (Y/N): "))
{
order.Cancel();
break;
}
}
}
else if (order.State is OrderConfirmedState)
{
Console.WriteLine("Order Preparation about to start");
Console.WriteLine("Press 1 to Cancel, or wait 5 seconds to continue...");
Console.WriteLine("1. Cancel");
DateTime endTime = DateTime.Now.AddSeconds(5);
bool cancelled = false;
while (DateTime.Now < endTime)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
if (key.KeyChar == '1')
{
order.Cancel();
cancelled = true;
break;
}
}
Thread.Sleep(100); // Don't burn CPU
}
if (!cancelled)
{
Console.WriteLine("No action taken. Starting preparation automatically.");
order.StartPreparation();
if (order.State == null) break;
}
}
order.StartDelivery();
if (order.State == null) break;
order.CompleteDelivery();
if (order.State == null) break;
order.State?.Archive();
if (order.State == null) break;
}
if (GetYesNoInput("Would you like to mark this order as favourite? (Y/N): "))
{
var markFavouriteCommand = new MarkAsFavouriteCommand(grabberoo, order);
var favouriteButton = new MarkAsFavouriteButton(markFavouriteCommand);
favouriteButton.Press();
}
}
/****** Favourite orders ******/
static void ViewFavouriteOrders(Grabberoo grabberoo, List<Restaurant> restaurants)
{
Console.WriteLine("\n--- Favourite Orders ---");
var favouriteOrders = grabberoo.GetFavouriteOrders().ToList();
if (favouriteOrders.Count == 0)
{
Console.WriteLine("No favourite orders found.");
return;
}
// Display favourite orders
for (int i = 0; i < favouriteOrders.Count; i++)
{
var order = favouriteOrders[i];
// Build a summary string of items
var itemsSummary = string.Join(", ",
order.OrderItems.Select(item => $"{item.Name} x{item.Quantity}"));
string discountInfo = "";
if (order.Restaurant != null && order.Restaurant.StoreWideDiscount > 0)
{
discountInfo = $" | {order.Restaurant.StoreWideDiscount}% OFF";
}
Console.WriteLine($"{i + 1}. [{itemsSummary}] | Address: {order.DeliveryAddress} | Amount: {order.Amount:C} | Status: {order.PaymentStatus}{discountInfo}");
}
Console.WriteLine("\nOptions:");
Console.WriteLine("1. Remove a favourite order");
Console.WriteLine("2. Reorder a favourite order");
Console.WriteLine("3. Back to main menu");
int option = GetIntInput("Select an option (1-3): ", 1, 3);
if (option == 1)
{
int removeChoice = GetIntInput($"Select order to remove (1-{favouriteOrders.Count}): ", 1, favouriteOrders.Count);
var orderToRemove = favouriteOrders[removeChoice - 1];
var removeFavouriteCommand = new MarkAsFavouriteCommand(grabberoo, orderToRemove);
var favouriteButton = new MarkAsFavouriteButton(removeFavouriteCommand);
favouriteButton.Unpress();
}
else if (option == 2)
{
int reorderChoice = GetIntInput($"Select order to reorder (1-{favouriteOrders.Count}): ", 1, favouriteOrders.Count);
var originalOrder = favouriteOrders[reorderChoice - 1];
var newOrder = grabberoo.ReorderFavourite(originalOrder);
if (newOrder == null) return;
// Find the restaurant for delivery fee calculation
var selectedRestaurant = restaurants.FirstOrDefault(r => r.Address == originalOrder.DeliveryAddress)
?? restaurants[0];
// Store original amount before restaurant discount
double originalAmount = newOrder.OrderItems.Sum(item => item.Cost);
// Set the restaurant and apply discounts
newOrder.SetRestaurant(selectedRestaurant);
Console.WriteLine("\nChoose order type:");
Console.WriteLine("1. Standard Delivery");
Console.WriteLine("2. Express Delivery");
int orderType = GetIntInput("Enter choice (1-2): ", 1, 2);
OrderProcessor orderProcessor;
if (orderType == 1)
orderProcessor = new StandardOrderProcessor(newOrder, selectedRestaurant);
else
orderProcessor = new ExpressOrderProcessor(newOrder, selectedRestaurant);
orderProcessor.ProcessOrder();
double restaurantDeliveryPrice = selectedRestaurant.RestaurantDeliveryPrice;
double processorFee = 0;
if (orderProcessor is StandardOrderProcessor sop)
processorFee = sop.DeliveryFee;
else if (orderProcessor is ExpressOrderProcessor eop)
processorFee = eop.ExpressCharge;
double combinedDeliveryPrice = restaurantDeliveryPrice + processorFee;
double totalPrice = orderProcessor.CalculatePrice();
// Set the total price for payment processing
newOrder.TotalPrice = totalPrice;
// Display reorder summary
Console.WriteLine("\nReorder Summary:");
foreach (var item in newOrder.OrderItems)
{
Console.WriteLine($"- {item.Name} x{item.Quantity} ({item.Cost:C})");
}
Console.WriteLine($"Subtotal: {originalAmount:C}");
if (selectedRestaurant.StoreWideDiscount > 0)
{
double storeDiscountAmount = originalAmount - newOrder.Amount;
Console.WriteLine($"Restaurant Discount ({selectedRestaurant.StoreWideDiscount}%): -{storeDiscountAmount:C}");
Console.WriteLine($"Final Subtotal: {newOrder.Amount:C}");
}
Console.WriteLine($"Delivery price: {combinedDeliveryPrice:C}");
Console.WriteLine($"Total: {totalPrice:C}");
if (selectedRestaurant.StoreWideDiscount > 0)
{
double savings = originalAmount - newOrder.Amount;
Console.WriteLine($"\nYou saved {savings:C} with the restaurant discount!");
}
// State-driven workflow (same as PlaceOrder)
while (newOrder.State != null)
{
newOrder.Submit();
if (newOrder.State is PendingPaymentState)
{
Console.WriteLine("1. Pay");
Console.WriteLine("2. Cancel");
int choice = GetIntInput("Choose action: ", 1, 2);
if (choice == 1)
{
newOrder.Pay();
Console.WriteLine("Processing payment...");
Console.WriteLine("Press 1 to Cancel, or wait 5 seconds for restaurant response...");
Console.WriteLine("1. Cancel");
DateTime endTime = DateTime.Now.AddSeconds(5);
bool cancelled = false;
while (DateTime.Now < endTime)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
if (key.KeyChar == '1')
{
newOrder.Cancel();
cancelled = true;
break;
}
}
Thread.Sleep(100);
}
if (!cancelled)
{
// Simulate restaurant decision: 80% confirm, 20% reject
var rand = new Random();
int outcome = rand.Next(1, 101);
if (outcome <= 80)
{
Console.WriteLine("Restaurant has CONFIRMED your order.");
newOrder.Confirm();
}
else
{
Console.WriteLine("Restaurant has REJECTED your order.");
newOrder.Reject();
break;
}
}
else
{
break;
}
}
else newOrder.Cancel();
if (newOrder.State == null) break;
}
else if (newOrder.State is PendingConfirmationState)
{
if (newOrder.State != null)
{
if (GetYesNoInput("Would you like to cancel your order? (Y/N): "))
{
newOrder.Cancel();
break;
}
}
}
else if (newOrder.State is OrderConfirmedState)
{
Console.WriteLine("Order Preparation about to start");
Console.WriteLine("Press 1 to Cancel, or wait 5 seconds to continue...");
Console.WriteLine("1. Cancel");
DateTime endTime = DateTime.Now.AddSeconds(5);
bool cancelled = false;
while (DateTime.Now < endTime)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
if (key.KeyChar == '1')
{
newOrder.Cancel();
cancelled = true;
break;
}
}
Thread.Sleep(100);
}
if (!cancelled)
{
Console.WriteLine("No action taken. Starting preparation automatically.");
newOrder.StartPreparation();
if (newOrder.State == null) break;
}
}
newOrder.StartDelivery();
if (newOrder.State == null) break;
newOrder.CompleteDelivery();
if (newOrder.State == null) break;
newOrder.State?.Archive();
if (newOrder.State == null) break;
}
}
// else: Back to main menu
}
/****** Decorator application ******/
static OrderItem ApplyDecoratorsToItem(OrderItem orderItem)
{
foreach (var decoratorType in orderItem.MenuItem.GetAvailableDecorators())
{
var attr = decoratorType
.GetCustomAttributes(typeof(DecoratorDescriptionAttribute), false)
.Cast<DecoratorDescriptionAttribute>()
.FirstOrDefault() ?? throw new Exception($"Missing DecoratorDescription attribute for {decoratorType.Name}");
if (GetYesNoInput($"{attr?.Description}? (Y/N): "))
{
orderItem = (OrderItem)Activator.CreateInstance(decoratorType, orderItem)!;
}
}
return orderItem;
}
/****** Display helpers ******/
static void PrintMenu(Menu menu)
{
var i = 1;
var iter = menu.CreateIterator();
var indent = 0;
var itemsUntilUnindent = 0;
while (iter.HasNext())
{
if (itemsUntilUnindent > 0) itemsUntilUnindent--;
var item = (MenuComponent)iter.Next();
var prefix = item is MenuItem ? $"{i++}. " : "";
Console.WriteLine($"{new string(' ', indent)}{prefix}{item}");
if (itemsUntilUnindent == 0 && indent > 0) indent -= 2;
if (item is Menu m)
{
indent += 2;
itemsUntilUnindent += m.Components.Count;
}
}
}
/****** Input helpers ******/
static int GetIntInput(string prompt, int min, int max)
{
int value;
do
{
Console.Write(prompt);
string input = Console.ReadLine();
if (int.TryParse(input, out value) && value >= min && value <= max)
break;
Console.WriteLine($"Please enter a number between {min} and {max}.");
} while (true);
return value;
}
static string GetStringInput(string prompt)
{
string input;
do
{
Console.Write(prompt);
input = Console.ReadLine();
} while (string.IsNullOrWhiteSpace(input));
return input.Trim();
}
static bool IsValidEmail(string email)
{
return email.Contains("@") && email.Contains(".");
}
static bool IsAllDigits(string value)
{
foreach (char c in value)
{
if (!char.IsDigit(c))
return false;
}
return true;
}
static bool IsValidExpiryDate(string expiryDate)
{
if (string.IsNullOrWhiteSpace(expiryDate) || expiryDate.Length != 5 || expiryDate[2] != '/')
return false;
string[] parts = expiryDate.Split('/');
if (parts.Length != 2) return false;
if (!int.TryParse(parts[0], out int month) || !int.TryParse(parts[1], out int year))
return false;
if (month < 1 || month > 12)
return false;
int currentYear = DateTime.Now.Year % 100;
int currentMonth = DateTime.Now.Month;
if (year < currentYear)
return false;
if (year == currentYear && month < currentMonth)
return false;
return true;
}
static bool GetYesNoInput(string prompt)
{
string input;
do
{
Console.Write(prompt);
input = Console.ReadLine()?.Trim().ToUpper();
if (input == "Y") return true;
if (input == "N") return false;
Console.WriteLine("Please enter Y or N.");
} while (true);
}