Files
baytransitclis/bt.nim
2022-06-28 16:49:26 -07:00

64 lines
1.7 KiB
Nim

import std/[json, httpclient, sequtils, strutils, times]
import strformat
import os
import terminal
let client = newHttpClient()
proc getDepartures(station: string): JSONNode =
let response = client.get(&"http://api.bart.gov/api/etd.aspx?cmd=etd&orig={station}&key=MW9S-E7SL-26DU-VV8V&json=y")
parseJson(response.body)
proc formatEstimateMinutes(minutes: string): string =
case minutes:
of "Leaving":
"leaving"
of "1":
"1 min"
else:
&"{minutes} mins"
proc lineColor(color: string): ForegroundColor =
case color.toLowerAscii():
of "blue": fgBlue
of "green": fgGreen
of "red": fgRed
of "yellow": fgYellow
of "orange": fgMagenta
else: fgDefault
proc formatDepartures(etd: JSONNode): string =
let name = etd["root"]["station"][0]["name"].getStr
let lines = etd["root"]["station"][0]["etd"]
styledEcho styleBright, name & " - " & now().format("H:mm")
let maxDestLength = lines.map(proc (line: JSONNode) = line["destination"].getStr.len).foldl(max(a,b), 1)
for line in lines:
let dest = line["destination"].getStr
let color = line["estimate"][0]["color"].getStr
var estimate = formatEstimateMinutes(line["estimate"][0]["minutes"].getStr)
if len(line["estimate"]) > 1:
estimate = estimate & ", " & formatEstimateMinutes(line["estimate"][1]["minutes"].getStr)
styledEcho lineColor(color), &"{dest}\t\t{estimate}"
proc usage() =
echo """bt - bart times cli
usage: bt station [direction n or s]
"""
proc main =
let params = commandLineParams()
if len(params) == 0:
usage()
elif len(params) == 1:
let station = params[0]
echo formatDepartures(getDepartures(station))
main()