summary refs log tree commit diff
path: root/testFrontend/SafeNSound.FakeUser/UserService.cs
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2025-06-03 23:38:36 +0200
committerRory& <root@rory.gay>2025-06-03 23:38:50 +0200
commit7ed1b77457f5e41ec5f7ba8e102f13f69380608d (patch)
tree22cbb57a43dfae7cc4458c1e13b3b5ae20595815 /testFrontend/SafeNSound.FakeUser/UserService.cs
parentPrepare for budgeting, move to native createdAt (diff)
downloadnodejs-final-assignment-7ed1b77457f5e41ec5f7ba8e102f13f69380608d.tar.xz
Implement budget handling
Diffstat (limited to 'testFrontend/SafeNSound.FakeUser/UserService.cs')
-rw-r--r--testFrontend/SafeNSound.FakeUser/UserService.cs59
1 files changed, 59 insertions, 0 deletions
diff --git a/testFrontend/SafeNSound.FakeUser/UserService.cs b/testFrontend/SafeNSound.FakeUser/UserService.cs
new file mode 100644

index 0000000..e717458 --- /dev/null +++ b/testFrontend/SafeNSound.FakeUser/UserService.cs
@@ -0,0 +1,59 @@ +namespace SafeNSound.FakeUser; + +public class UserService(ILogger<UserService> logger, UserStore userStore) : IHostedService { + private Task _alarmTask, _spendBudgetTask; + private readonly CancellationTokenSource _cts = new(); + + public async Task StartAsync(CancellationToken cancellationToken) { + _alarmTask = ManageAlarms(_cts.Token); + _spendBudgetTask = AssignBudget(_cts.Token); + } + + private static readonly string[] validReasons = ["fall", "toilet"]; + + private async Task ManageAlarms(CancellationToken cancellationToken) { + while (!cancellationToken.IsCancellationRequested) { + try { + var user = userStore.GetRandomUser(); + var currentAlarm = await user.Client!.GetAlarm(); + if (currentAlarm is null) { + await user.Client!.SetAlarm(new Sdk.AlarmDto { + Reason = Random.Shared.GetItems(validReasons, 1).First() + }); + } + else { + await user.Client!.DeleteAlarm(); + } + } + catch (Exception ex) { + logger.LogError(ex, "Error setting/deleting alarm"); + } + + await Task.Delay(TimeSpan.FromMilliseconds(250), cancellationToken); + } + } + + private async Task AssignBudget(CancellationToken cancellationToken) { + while (!cancellationToken.IsCancellationRequested) { + try { + var user = userStore.GetRandomUser(); + var budget = await user.Client!.GetBudget(); + await user.Client!.SpendBudget(new() { + Amount = Math.Min(budget.Amount, Random.Shared.NextDouble()), + Reason = "Random budget spending", + Venue = "The Store" + }); + await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); + } + catch (Exception ex) { + logger.LogError(ex, "Error spending budget"); + } + } + } + + public async Task StopAsync(CancellationToken cancellationToken) { + await _cts.CancelAsync(); + await _alarmTask; + await _spendBudgetTask; + } +} \ No newline at end of file