aboutsummaryrefslogtreecommitdiff
path: root/src/Enmarcha.Backend/Services/Processors/VitrasaUsageProcessor.cs
blob: a2f90d3c1318492d48771917bf00da8ed6c7f7ae (plain)
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
using System.Text.Json;
using Enmarcha.Backend.Types.Arrivals;
using Microsoft.Extensions.Caching.Memory;

namespace Enmarcha.Backend.Services.Processors;

public class VitrasaUsageProcessor : IArrivalsProcessor
{
    private readonly HttpClient _httpClient;
    private readonly IMemoryCache _cache;
    private readonly ILogger<VitrasaUsageProcessor> _logger;
    private readonly FeedService _feedService;

    public VitrasaUsageProcessor(
        HttpClient httpClient,
        IMemoryCache cache,
        ILogger<VitrasaUsageProcessor> logger,
        FeedService feedService)
    {
        _httpClient = httpClient;
        _cache = cache;
        _logger = logger;
        _feedService = feedService;
    }

    public async Task ProcessAsync(ArrivalsContext context)
    {
        if (!context.StopId.StartsWith("vitrasa:") || context.IsReduced || context.IsNano) return;

        var normalizedCode = _feedService.NormalizeStopCode("vitrasa", context.StopCode);

        var cacheKey = $"vigo_usage_{normalizedCode}";
        if (_cache.TryGetValue(cacheKey, out List<BusStopUsagePoint>? cachedUsage))
        {
            context.Usage = cachedUsage;
            return;
        }

        try
        {
            using var activity = Telemetry.Source.StartActivity("FetchVigoUsage");
            var url = $"https://datos.vigo.org/vci_api_app/api2.jsp?tipo=TRANSPORTE_PARADA_HORAS_USO&parada={normalizedCode}";
            var response = await _httpClient.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                var usage = JsonSerializer.Deserialize<List<BusStopUsagePoint>>(json);

                if (usage != null)
                {
                    _cache.Set(cacheKey, usage, TimeSpan.FromDays(7));
                    context.Usage = usage;
                }
            }
            else
            {
                _logger.LogWarning("Failed to fetch usage data for stop {StopCode}, status: {Status}", normalizedCode, response.StatusCode);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error fetching usage data for Vigo stop {StopCode}", normalizedCode);
        }
    }
}