Skip to content

Commit

Permalink
fix: correct relative time calculation with delay
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaya-Sem committed Aug 18, 2024
1 parent 4e7e7ce commit a74f6e0
Show file tree
Hide file tree
Showing 6 changed files with 127 additions and 28 deletions.
20 changes: 19 additions & 1 deletion cmd/api/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"fmt"
"io"
"net/http"
"os"
"strconv"
)

// GetConnections fetches the connection data from the API and returns the response body as a byte slice.
Expand Down Expand Up @@ -41,7 +43,23 @@ func ParseConnections(body []byte) ([]Connection, error) {
return result.Connection, nil
}

// Struct definitions remain the same.
func (c Connection) GetDelayInSeconds() int {
delay, err := strconv.Atoi(c.Departure.Delay)

if err != nil {
fmt.Printf("Error converting delay: %s", c.Departure.Time)
os.Exit(1)
}
return delay
}

func (c Connection) GetUnixDepartureTime() int {
depTime, err := strconv.Atoi(c.Departure.Time)
if err != nil {
fmt.Println("Error converting departuretime: %s", c.Departure.Time)
}
return depTime
}

type ConnectionResult struct {
Connection []Connection `json:"connection"`
Expand Down
22 changes: 22 additions & 0 deletions cmd/api/timetableDepartureStruct.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
package api

import (
"fmt"
"strconv"
)

func (d TimetableDeparture) GetUnixDepartureTime() int {
time, err := strconv.Atoi(d.Time)
if err != nil {
fmt.Println("Error converting departure time: %s", d.Time)
}

return time
}

func (d TimetableDeparture) GetDelayInSeconds() int {
delay, err := strconv.Atoi(d.Delay)
if err != nil {
fmt.Println("Error converting delay: %s", d.Delay)
}
return delay
}

type StationTimetableResponse struct {
Version string `json:"version"`
Timestamp string `json:"timestamp"`
Expand Down
5 changes: 3 additions & 2 deletions cmd/tables/connectionTable.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,13 @@ func (m connectionTableModel) Init() tea.Cmd { return nil }

func getDetailedConnectionInfo(c api.Connection) string {
return fmt.Sprintf(`
Detailed info:
Departure in %s
Destination: %s
Track: %s
Departure Time: %s
Vehicle: %s
`,
CalculateHumanRelativeTime(c),
c.Departure.Station,
c.Departure.Platform,
cmd.UnixToHHMM(c.Departure.Time),
Expand All @@ -44,7 +45,7 @@ func (m *connectionTableModel) updateSelectedDetails() {

m.selectedDetails = getDetailedConnectionInfo(selectedConnection)
} else {
m.selectedDetails = "No row selected" // Should never really happen
m.selectedDetails = "Nothing found!"
}
}

Expand Down
50 changes: 27 additions & 23 deletions cmd/tables/tableUtil.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,30 @@ package table

import (
"fmt"
"github.com/charmbracelet/lipgloss"
"time"

"github.com/charmbracelet/lipgloss"
)

const ()

const (
BorderColor = "240" // gray
SelectedForeground = "15" // white
SelectedBackground = "97" // mauve
Gray = "240"
White = "15"
Mauve = "97"
BorderColor = Gray
SelectedForeground = White
SelectedBackground = Mauve
tableHeight = 10
)

var (
lowOccupancyStyle = lipgloss.NewStyle().Italic(true).Foreground(lipgloss.Color("2")) // green
mediumOccupancyStyle = lipgloss.NewStyle().Italic(true).Foreground(lipgloss.Color("214")) // orange
highOccupancyStyle = lipgloss.NewStyle().Italic(true).Foreground(lipgloss.Color("9")) // red
unknownOccupancyStyle = lipgloss.NewStyle().Italic(true).Faint(true).Italic(true)
baseOccupancyStyle = lipgloss.NewStyle().Italic(true)

lowOccupancyStyle = baseOccupancyStyle.Copy().Foreground(lipgloss.Color("2")) // green
mediumOccupancyStyle = baseOccupancyStyle.Copy().Foreground(lipgloss.Color("214")) // orange
highOccupancyStyle = baseOccupancyStyle.Copy().Foreground(lipgloss.Color("9")) // red
unknownOccupancyStyle = baseOccupancyStyle.Copy().Faint(true)
)

func styleOccupancy(s string) string {
Expand All @@ -33,25 +41,21 @@ func styleOccupancy(s string) string {
}
}

// CalculateHumanRelativeTime used for calucating human-readable "from now" time. E.g 'in 20 minutes'
func CalculateHumanRelativeTime(departureTime string) string {
now := time.Now()
type timeable interface {
GetUnixDepartureTime() int
GetDelayInSeconds() int
}

depTime, err := time.Parse("15:04", departureTime)
if err != nil {
return ""
}
// TODO: add delay onto the time

// Combine the parsed time with today's date
depDateTime := time.Date(now.Year(), now.Month(), now.Day(), depTime.Hour(), depTime.Minute(), 0, 0, now.Location())
func CalculateHumanRelativeTime(t timeable) string {
now := time.Now()

// If the departure time is earlier than now, assume it's for the next day
if depDateTime.Before(now) {
depDateTime = depDateTime.Add(24 * time.Hour)
}
depTime := time.Unix(int64(t.GetUnixDepartureTime()), 0)
depTime = depTime.Add(time.Duration(t.GetDelayInSeconds()) * time.Second)

// Calculate the duration between now and the departure time
duration := depDateTime.Sub(now)
// Calculate the duration between now and the adjusted departure time
duration := depTime.Sub(now)

// Handle special cases
if duration < 1*time.Minute {
Expand Down
53 changes: 53 additions & 0 deletions cmd/tables/tableUtil_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package table

import (
"testing"
"time"
)

type mockTimeable struct {
unixTime int
delay int
}

func (m mockTimeable) GetUnixDepartureTime() int {
return m.unixTime
}

func (m mockTimeable) GetDelayInSeconds() int {
return m.delay
}

// Test for CalculateHumanRelativeTime function
func TestCalculateHumanRelativeTime(t *testing.T) {
now := time.Now()

tests := []struct {
unixTime int
delay int
expected string
}{
// Event is happening now (no delay)
{int(now.Unix()), 0, "now"},
// Event in 5 minutes (no delay)
{int(now.Add(5 * time.Minute).Unix()), 0, "4 min"},
// Event in 1 hour (no delay)
{int(now.Add(1 * time.Hour).Unix()), 0, "59 min"},
// Event in 1 hour and 30 minutes (no delay)
{int(now.Add(1*time.Hour + 30*time.Minute).Unix()), 0, "1 hour 29 min"},
// Event in 2 hours (no delay)
{int(now.Add(2 * time.Hour).Unix()), 0, "1 hour 59 min"},
// Event is 30 minutes ago but with 1-hour delay
{int(now.Add(-30 * time.Minute).Unix()), 3600, "29 min"},
// Event in 45 minutes (30 minutes delay)
{int(now.Add(15 * time.Minute).Unix()), 1800, "44 min"},
}

for _, test := range tests {
mock := mockTimeable{unixTime: test.unixTime, delay: test.delay}
result := CalculateHumanRelativeTime(mock)
if result != test.expected {
t.Errorf("CalculateHumanRelativeTime(%v) = %s; want %s", mock, result, test.expected)
}
}
}
5 changes: 3 additions & 2 deletions cmd/tables/timetableTable.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type timetableTableModel struct {
func (m timetableTableModel) Init() tea.Cmd { return nil }

func getDetailedDepartureInfo(d api.TimetableDeparture) string {
relativeTime := CalculateHumanRelativeTime(d.Time)
relativeTime := CalculateHumanRelativeTime(d)
return fmt.Sprintf(`
Departure in: %s
Track: %s
Expand All @@ -47,7 +47,7 @@ func (m *timetableTableModel) updateSelectedDetails() {
// Update the selected details including the relative time
m.selectedDetails = getDetailedDepartureInfo(selectedDeparture)
} else {
m.selectedDetails = "No row selected" // Should never really happen
m.selectedDetails = "Nothing found!"
}
}

Expand Down Expand Up @@ -77,6 +77,7 @@ func (m timetableTableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, teaCmd
}

// TODO: export to consts
var detailsBoxStyle = lipgloss.NewStyle().Padding(1)

func (m timetableTableModel) View() string {
Expand Down

0 comments on commit a74f6e0

Please sign in to comment.