#!/usr/bin/python3

import urllib.request
import urllib.request
import json

# get token
print("Authenticating…")
urllib.request.urlretrieve("https://iphone.dsbcontrol.de/iPhoneService.svc/DSB/authid/AUTHID/AUTHPASS", "token.json")

with open('token.json') as json_data:
    token = json.load(json_data)

print("Got token: " + token + "\n")


# get timetable url
print("Getting url…")

urllib.request.urlretrieve("https://iphone.dsbcontrol.de/iPhoneService.svc/DSB/timetables/" + token, "timetables.json")

timetables = open("timetables.json", "r").read()
print("Loaded JSON: " + timetables)

with open('timetables.json') as json_data:
    data = json.load(json_data)
    url = data[0]["timetableurl"]
    print("Got url: " + url + "\n")


# open url
print("Opening browser…")
from subprocess import call
call(["lynx", url])

# clean up
call(["rm", "timetables.json"])
call(["rm", "token.json"])
