summary refs log tree commit diff
path: root/testFrontend/SafeNSound.FakeUser/UserService.cs
blob: e717458086ba91805b428bc87b8eb92745d0ff6d (plain) (blame)
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
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;
    }
}