using System.Net.Http.Headers;
using System.Text.Json;
using AttendanceHub.Sync.Workers;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AttendanceHub.Sync.Configuration;
///
/// Device-list source configuration. The authoritative list of devices (count, IP, port, comm key)
/// comes from the Laravel API — exactly like the original web service — so adding/removing a device
/// in the panel is picked up by the service without editing local files.
///
public sealed class DevicesConfig
{
/// "laravel" = dynamic list from the API, anything else = the single static device.
public string Source { get; set; } = "static";
/// Base address of the Laravel app. Falls back to the upload baseAddress.
public string BaseAddress { get; set; } = "";
public string ListPath { get; set; } = "/api/v1/devices";
/// Bearer token. Falls back to the upload apiToken (same sync token).
public string ApiToken { get; set; } = "";
/// How often the list is refreshed (dynamic add/remove of devices).
public int RefreshSeconds { get; set; } = 60;
/// When the API is unreachable and no cached list exists, fall back to the static device.
public bool FallbackToStatic { get; set; } = true;
public int MachineNumber { get; set; } = 1;
/// Optional ip → local device-id overrides (keeps an existing SQLite identity stable).
public Dictionary IdOverrides { get; set; } = new(StringComparer.OrdinalIgnoreCase);
}
public static class DevicesConfigParser
{
/// Parse the optional "devices" section. Returns null when the section is absent.
public static DevicesConfig? ParseFromFile(string configPath)
{
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(configPath));
if (!doc.RootElement.TryGetProperty("devices", out var el) || el.ValueKind != JsonValueKind.Object)
return null;
var cfg = new DevicesConfig();
if (el.TryGetProperty("source", out var src)) cfg.Source = src.GetString() ?? cfg.Source;
if (el.TryGetProperty("baseAddress", out var ba)) cfg.BaseAddress = ba.GetString() ?? "";
if (el.TryGetProperty("listPath", out var lp)) cfg.ListPath = lp.GetString() ?? cfg.ListPath;
if (el.TryGetProperty("apiToken", out var tk)) cfg.ApiToken = tk.GetString() ?? "";
if (el.TryGetProperty("refreshSeconds", out var rs) && rs.TryGetInt32(out var rsi)) cfg.RefreshSeconds = Math.Max(5, rsi);
if (el.TryGetProperty("fallbackToStatic", out var fs)) cfg.FallbackToStatic = fs.ValueKind == JsonValueKind.True;
if (el.TryGetProperty("machineNumber", out var mn) && mn.TryGetInt32(out var mni)) cfg.MachineNumber = mni;
if (el.TryGetProperty("idOverrides", out var ov) && ov.ValueKind == JsonValueKind.Object)
{
foreach (var prop in ov.EnumerateObject())
{
var value = prop.Value.GetString();
if (!string.IsNullOrWhiteSpace(value))
cfg.IdOverrides[prop.Name] = value;
}
}
// Defaults for base address / token come from the "upload" section, but INDEPENDENTLY of
// upload.enabled: acquisition (device list) must never depend on delivery being switched on.
if (doc.RootElement.TryGetProperty("upload", out var up) && up.ValueKind == JsonValueKind.Object)
{
if (string.IsNullOrWhiteSpace(cfg.BaseAddress) && up.TryGetProperty("baseAddress", out var uba))
cfg.BaseAddress = uba.GetString() ?? "";
if (string.IsNullOrWhiteSpace(cfg.ApiToken) && up.TryGetProperty("apiToken", out var utk))
cfg.ApiToken = utk.GetString() ?? "";
}
return cfg;
}
catch (Exception)
{
return null; // malformed/absent => caller keeps static behaviour
}
}
}
///
/// Periodically resolves the device list (Laravel) and exposes the last known-good snapshot.
/// Never applies an empty list over a non-empty one (a glitchy response must not tear devices down)
/// and always keeps the previous snapshot when a refresh fails.
///
public sealed class DeviceRegistry : IAsyncDisposable
{
private readonly DevicesConfig _cfg;
private readonly HttpClient _http;
private readonly DeviceEndpoint? _staticFallback;
private readonly ILogger _log;
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly CancellationTokenSource _cts = new();
private Task? _loop;
private List _current = [];
public DeviceRegistry(DevicesConfig cfg, HttpClient http, DeviceEndpoint? staticFallback = null, ILogger? log = null)
{
_cfg = cfg;
_http = http;
_staticFallback = staticFallback;
_log = log ?? NullLogger.Instance;
}
public IReadOnlyList Current
{
get
{
lock (_current) return _current.ToList();
}
}
/// Raised after every successful refresh that changed the resolved list.
public event Action>? Updated;
/// Resolve the list once (blocking, used for startup).
public Task> RefreshAsync(CancellationToken cancellationToken = default)
=> RefreshCoreAsync(cancellationToken);
/// Start the periodic refresh loop.
public Task StartAsync(CancellationToken cancellationToken = default)
{
if (!string.Equals(_cfg.Source, "laravel", StringComparison.OrdinalIgnoreCase))
return Task.CompletedTask;
_loop = Task.Run(() => LoopAsync(_cts.Token), CancellationToken.None);
return Task.CompletedTask;
}
private async Task LoopAsync(CancellationToken ct)
{
var interval = TimeSpan.FromSeconds(Math.Max(5, _cfg.RefreshSeconds));
while (!ct.IsCancellationRequested)
{
try
{
await Task.Delay(interval, ct).ConfigureAwait(false);
await RefreshCoreAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_log.LogError(ex, "DEVICE_LIST_REFRESH_ERROR — previous device list kept");
}
}
}
private async Task> RefreshCoreAsync(CancellationToken ct)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
if (!string.Equals(_cfg.Source, "laravel", StringComparison.OrdinalIgnoreCase))
return Apply(StaticOnly());
List fetched;
try
{
fetched = await FetchAsync(ct).ConfigureAwait(false);
}
catch (Exception ex)
{
_log.LogWarning(ex, "DEVICE_LIST_FETCH_FAILED — keeping {N} known device(s)", Current.Count);
if (Current.Count > 0)
return Current;
if (_cfg.FallbackToStatic && _staticFallback is not null)
return Apply([_staticFallback]);
return Current;
}
if (fetched.Count == 0)
{
if (Current.Count > 0)
{
_log.LogWarning("DEVICE_LIST_EMPTY — ignoring empty response, keeping {N} known device(s)", Current.Count);
return Current;
}
if (_cfg.FallbackToStatic && _staticFallback is not null)
return Apply([_staticFallback]);
return Apply([]);
}
return Apply(fetched);
}
finally
{
_gate.Release();
}
}
private List StaticOnly()
=> _staticFallback is null ? [] : [_staticFallback];
private IReadOnlyList Apply(List list)
{
var changed = false;
lock (_current)
{
changed = !list.Select(d => d.DeviceId).SequenceEqual(_current.Select(d => d.DeviceId), StringComparer.OrdinalIgnoreCase);
_current = list;
}
if (changed)
_log.LogInformation("DEVICE_LIST_APPLIED count={N} devices={List}", list.Count,
string.Join(",", list.Select(d => d.DeviceId)));
if (changed)
Updated?.Invoke(list);
return list;
}
private async Task> FetchAsync(CancellationToken ct)
{
var baseUrl = _cfg.BaseAddress.TrimEnd('/');
var path = _cfg.ListPath.StartsWith('/') ? _cfg.ListPath : "/" + _cfg.ListPath;
var uri = new Uri(baseUrl + path);
using var request = new HttpRequestMessage(HttpMethod.Get, uri);
if (!string.IsNullOrEmpty(_cfg.ApiToken))
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _cfg.ApiToken);
request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
using var response = await _http.SendAsync(request, ct).ConfigureAwait(false);
var body = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
throw new HttpRequestException($"GET {uri} -> {(int)response.StatusCode}");
using var doc = JsonDocument.Parse(body);
var root = doc.RootElement;
var result = new List();
if (!root.TryGetProperty("devices", out var devices) || devices.ValueKind != JsonValueKind.Array)
return result;
foreach (var el in devices.EnumerateArray())
{
var ip = el.TryGetProperty("ip", out var ipEl) ? ipEl.GetString()?.Trim() : null;
if (string.IsNullOrWhiteSpace(ip))
continue;
var port = el.TryGetProperty("port", out var portEl) && portEl.TryGetInt32(out var p) && p > 0 ? p : 4370;
var commKey = el.TryGetProperty("comm_key", out var ckEl) && ckEl.TryGetInt32(out var ck) ? ck : 0;
var name = el.TryGetProperty("name", out var nameEl) ? nameEl.GetString() ?? ip : ip;
var id = el.TryGetProperty("id", out var idEl) && idEl.ValueKind == JsonValueKind.Number ? idEl.GetInt64() : 0;
// Local identity: the API id is carried in the display name; the operational id is the IP
// (which is also what Laravel expects in records[].device_id), unless overridden.
var localId = _cfg.IdOverrides.TryGetValue(ip, out var overridden) ? overridden : ip;
var displayName = string.IsNullOrWhiteSpace(name) ? ip : $"{name} (#{id})";
if (result.Any(d => string.Equals(d.DeviceId, localId, StringComparison.OrdinalIgnoreCase)))
continue;
result.Add(new DeviceEndpoint(localId, displayName, ip, port, _cfg.MachineNumber, commKey));
}
return result;
}
public ValueTask DisposeAsync()
{
_cts.Cancel();
_cts.Dispose();
_gate.Dispose();
return ValueTask.CompletedTask;
}
}