summary refs log tree commit diff
path: root/testFrontend/SafeNSound.Demo/Pages/User.razor
blob: cdffbe316cc76cabcbcf43630c601afc10d99d3d (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@page "/User"
@implements IDisposable
@if (_isInitialized) {
    <h3>User (@WhoAmI.UserId#@WhoAmI.DeviceId[..5])</h3>
    <LinkButton OnClick="@(() => {
                             NavigationManager.NavigateTo("/User/Devices");
                             return Task.CompletedTask;
                         })">Manage devices
    </LinkButton>
    <hr/>

    <span>
        Raise alarm:
        <LinkButton OnClick="@(() => RaiseAlarm("fall"))">Fall</LinkButton>
        <LinkButton OnClick="@(() => RaiseAlarm("toilet"))">Toilet</LinkButton>
        <LinkButton Color="#FF0000" OnClick="@(() => RaiseAlarm(null))">Clear</LinkButton>
    </span>
    <br/>
}

@if (Alarm != null) {
    <ModalWindow Title="User alarm">
        <div class="modal-body">
            <span><strong>Alarm ID:</strong> @Alarm.Id</span><br/>
            <span><strong>Reason:</strong> @Alarm.Reason</span><br/>
            <span><strong>Raised at:</strong> @Alarm.CreatedAt.ToLocalTime()</span><br/>
        </div>
        <div class="modal-footer">
            <LinkButton Color="#FF0000" OnClick="@(() => RaiseAlarm(null))">Clear Alarm</LinkButton>
        </div>
    </ModalWindow>
}

@code {

    bool _isInitialized = false;
    bool _running = true;

    private WhoAmI WhoAmI { get; set; } = null!;
    private AlarmDto? Alarm { get; set; } = null!;

    protected override async Task OnInitializedAsync() {
        WhoAmI = await App.UserClient.WhoAmI();
        _isInitialized = true;
        _ = PollAlarm();
        NavigationManager.LocationChanged += (sender, args) => {
            if (args.Location != NavigationManager.Uri) {
                _running = false; // Stop polling when navigating away
            }
        };
    }

    private async Task PollAlarm() {
        while (_running) {
            var newAlarm = await App.UserClient.GetAlarm();
            if (Alarm?.Id != newAlarm?.Id) {
                Alarm = newAlarm;
                StateHasChanged();
            }

            await Task.Delay(1000);
        }
    }

    private async Task RaiseAlarm(string? reason) {
        if (string.IsNullOrWhiteSpace(reason))
            await App.UserClient.DeleteAlarm();
        else
            await App.UserClient.SetAlarm(new() { Reason = reason });
    }

    private void ReleaseUnmanagedResources() {
        _running = false;
    }

    public void Dispose() {
        ReleaseUnmanagedResources();
        GC.SuppressFinalize(this);
    }

    ~User() => ReleaseUnmanagedResources();

}