summary refs log tree commit diff
path: root/testFrontend/SafeNSound.FakeUser/RandomAlarmService.cs
blob: a2e133f80686e038df69340a1ccf3c8868fc0499 (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
namespace SafeNSound.FakeUser;

public class RandomAlarmService(UserStore userStore) : IHostedService {
    private Task? _listenerTask;
    private readonly CancellationTokenSource _cts = new();

    public async Task StartAsync(CancellationToken cancellationToken) {
        _listenerTask = Run(_cts.Token);
    }

    private static readonly string[] validReasons = ["fall", "toilet"];

    private async Task Run(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) {
                Console.WriteLine($"Error setting/deleting alarm: {ex.Message}");
            }

            await Task.Delay(TimeSpan.FromMilliseconds(250), cancellationToken);
        }
    }

    public async Task StopAsync(CancellationToken cancellationToken) {
        await _cts.CancelAsync();
    }
}