#!/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
info_timeout = 15  # seconds

# 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.SensorInfoRequest(token=token)

# call the API method
res = stub.GetSensorInfo(req)

# print result
print(f'API returned {len(res.sensorInfo)} sensors for this token:')
for info in res.sensorInfo:
    print("\t{} ({}, alias {}): located at {:.4f},{:.4f} (current fix: {})".format(
        info.sensor.serial, pb.Sensor.Type.Name(info.sensor.type), info.alias,
        info.gnss.position.latitude, info.gnss.position.longitude,
        pb.GNSSInformation.Position.FixType.Name(info.gnss.position.fix_type)))

# subscribe to target reports for 10 seconds
res = stub.GetTargetReports(pb.TargetReportsRequest(token=token))

print("Retrieving target reports for 10 seconds.")

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

    # count and store
    cnt += 1
    aircraft[tgt.target.address] = tgt

    if tgt.dropped_reports - dropped > 0:
        print(f'Reports were dropped: {tgt.dropped_reports}')
        dropped = tgt.dropped_reports

# graceful shutdown
res.cancel()

print("Done! We received {} reports from {} targets.".format(cnt, len(aircraft)))

# print some stats
adsb_cnt = 0
mlat_cnt = 0
for report in aircraft.values():
    now_ms = time.time() * 1000

    if report.HasField('mlat') and now_ms - report.mlat.tx_timestamp / 1_000_000 < info_timeout * 1000:
        mlat_cnt += 1

    if report.HasField('adsb') and now_ms - report.adsb.position_last_seen < info_timeout * 1000:
        adsb_cnt += 1

if aircraft:
    print(next(iter(aircraft.values())))

print("Out of {} targets, {} had an ADS-B position and {} were also tracked by MLAT.".format(
    len(aircraft), adsb_cnt, mlat_cnt))
