#!/usr/bin/python

"""
This example shows how to use the public SecureTrack gRPC API.
"""

# 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
duration = 10

# create channel and stub
cert = open(ca_cert, 'rb').read()
credentials = grpc.ssl_channel_credentials(cert)
ch = grpc.secure_channel(address, credentials)
stub = st.SeRoAPIStub(ch)

# create request for retrieving my sensors
req = pb.ModeSDownlinkFramesRequest(token=token)

print(f'Retrieving Mode S replies for {duration} seconds.')

res = stub.GetModeSDownlinkFrames(req)

start = time.time()
aircraft = dict()
cnt = 0
dropped = 0
for rply in res:
    if time.time() - start > duration:
        break

    if not rply.receptions:
        continue

    # count and store
    cnt += 1
    if rply.target.address in aircraft:
        aircraft[rply.target.address] += 1
    else:
        aircraft[rply.target.address] = 1

    if rply.dropped_frames > dropped:
        print(f'Frames were dropped: {rply.dropped_frames}')
        dropped = rply.dropped_frames

# graceful shutdown
res.cancel()

print("Done! We received {} replies from {} targets.".format(cnt, len(aircraft)))
print(f'We dropped {dropped} replies.')
