import json
import urllib.request
from django.conf import settings
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Loads HSL timetables and save to json file.'

    def handle(self, *args, **options):
        src = urllib.request.urlopen("http://api.reittiopas.fi/hsl/prod/?userhash="+settings.HSL_USERHASH+"&request=stops_area&center_coordinate=2545565,6675319").read().decode("utf-8")
        data = json.loads(src);
        arr=[]
        for element in data:
            src = urllib.request.urlopen("http://api.reittiopas.fi/hsl/prod/?userhash="+userhash+"&request=stop&code="+element['code']).read().decode("utf-8")
            parsed = json.loads(src)[0]
            arr.append({"name":parsed['name_fi'],"lines":parsed['lines'],"dist":element['dist'],"departures":parsed['departures']})
        with open('{}/hsl.json'.format(settings.MEDIA_ROOT),'w') as file:
            file.write(json.dumps(arr))
