aboutsummaryrefslogtreecommitdiff
path: root/src/Costasdev.Busurbano.Backend/Controllers/VigoController.Legacy.cs
blob: 3bb993085237dfe187692e95a217826712259aee (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
67
68
69
70
71
72
73
74
75
76
77
78
using System.Globalization;
using System.Text.Json;
using Costasdev.Busurbano.Backend.Types;
using Microsoft.AspNetCore.Mvc;
using SysFile = System.IO.File;

namespace Costasdev.Busurbano.Backend.Controllers;

public partial class VigoController : ControllerBase
{
    [HttpGet("GetStopEstimates")]
    public async Task<IActionResult> Run(
        [FromQuery] int id
    )
    {
        try
        {
            var response = await _api.GetStopEstimates(id);
            // Return only the estimates array, not the stop metadata
            return new OkObjectResult(response.Estimates);
        }
        catch (InvalidOperationException)
        {
            return BadRequest("Stop not found");
        }
    }

    [HttpGet("GetStopTimetable")]
    public async Task<IActionResult> GetStopTimetable(
    [FromQuery] int stopId,
    [FromQuery] string? date = null
)
    {
        // Use Europe/Madrid timezone to determine the correct date
        var tz = TimeZoneInfo.FindSystemTimeZoneById("Europe/Madrid");
        var nowLocal = TimeZoneInfo.ConvertTime(DateTime.UtcNow, tz);

        // If no date provided or date is "today", use Madrid timezone's current date
        string effectiveDate;
        if (string.IsNullOrEmpty(date) || date == "today")
        {
            effectiveDate = nowLocal.Date.ToString("yyyy-MM-dd");
        }
        else
        {
            // Validate provided date format
            if (!DateTime.TryParseExact(date, "yyyy-MM-dd", null, DateTimeStyles.None, out _))
            {
                return BadRequest("Invalid date format. Please use yyyy-MM-dd format.");
            }
            effectiveDate = date;
        }

        try
        {
            var file = Path.Combine(_configuration.ScheduleBasePath, effectiveDate, stopId + ".json");
            if (!SysFile.Exists(file))
            {
                throw new FileNotFoundException();
            }

            var contents = await SysFile.ReadAllTextAsync(file);

            return new OkObjectResult(JsonSerializer.Deserialize<List<ScheduledStop>>(contents)!);
        }
        catch (FileNotFoundException ex)
        {
            _logger.LogError(ex, "Stop data not found for stop {StopId} on date {Date}", stopId, effectiveDate);
            return StatusCode(404, $"Stop data not found for stop {stopId} on date {effectiveDate}");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error loading stop data");
            return StatusCode(500, "Error loading timetable");
        }
    }

}