import requests
import json


def bus_arrivals(naptan_id: str):
    """Use TFL API to return a list of bus arrivals at the parm bus stop. Each item in the list is a tuple of
       important info about the arrival. Buses in the list are sorted, with soonest arrival first.
       If the TFL API fails to respond then None will be returned.
       If there are no buses expected then an empty list will be returned.
    """

    arrivals_url = 'https://api.tfl.gov.uk/StopPoint/' + naptan_id + '/arrivals'

    request = requests.get(url=arrivals_url)        # Invoke the TFL API.

    if request.status_code != 200:
        return None
    else:
        request_list = json.loads(s=request.text)       # Convert JSON to list of dictionaries.

        bus_list = []

        for rl in request_list:
            exp_arrival_secs = rl.get('timeToStation')
            exp_arrival_mins = int(exp_arrival_secs / 60)
            bus_stop_name = rl.get('stationName')
            bus_number = rl.get('lineId')
            towards = rl.get('towards')

            bus_list.append((exp_arrival_secs, exp_arrival_mins, bus_stop_name, bus_number, towards))

        # Sorted by first item in each tuple, which is the number of seconds until arrival. This mean the list is sorted
        # to have the first bus which will arrival at the head of the list.
        return sorted(bus_list)