#!/usr/bin/python

"""
This example shows how to use the public SecureTrack gRPC API in an asynchronous
fashion using asyncio.
"""

# Python's asynchronous I/O library
import asyncio
# API-specific imports
import grpc  # basic gRPC functions
# some basic imports
import time

import SeRoAPI_pb2 as pb  # SecureTrack API SerDes
import SeRoAPI_pb2_grpc as st  # SecureTrack API stubs

# some configuration
token = 'INSERT YOUR TOKEN HERE'
address = 'api.secureadsb.com:4201'
ca_cert = 'ca.crt'  # point this to the ca.crt file


# subscribes to target reports for 10 seconds
async def stream_handler():
    global token, address
    # Note: channel will be closed automatically when we leave the with statement
    cert = open(ca_cert, 'rb').read()
    credentials = grpc.ssl_channel_credentials(cert)
    async with grpc.aio.secure_channel(address, credentials) as channel:
        print("Starting to retrieve data for 10 seconds.")
        stub = st.SeRoAPIStub(channel)
        it = stub.GetTargetReports(pb.TargetReportsRequest(token=token))
        tgts = dict()
        start = time.time()
        try:
            async for tgt in it.__aiter__():
                if time.time() - start > 10:
                    break

                tgts[tgt.target.address] = tgt
        except grpc.RpcError as e:
            print(e)

        it.cancel()

        print('I am also done retrieving data.')
        print(f'We have seen {len(tgts)} different aircraft.')


# sleeps for 5 seconds
async def chiller():
    print("In the meantime, I am going to chill for 5 seconds.")
    await asyncio.sleep(5)
    print("Feeling pretty relaxed now. Returning to main!")


# run the two above methods in parallel
async def main():
    await asyncio.gather(stream_handler(), chiller())


print("Calling async main method.")
asyncio.run(main())
print("Exiting, bye bye.")
