from datetime import datetime
import json
import hashlib


def map_aircraft_to_record(aircrafts, message_now, device_id):
  """
  Maps the `aircraft` entity to a BigQuery record and its unique id.
  Returns `(unique_ids, records)`
  """
  def copy_data(aircraft):
    result = {
      'hex': aircraft.get('hex'),
      'squawk': aircraft.get('squawk'),
      'flight': aircraft.get('flight'),
      'lat': aircraft.get('lat'), 
      'lon': aircraft.get('lon'), 
      'nucp': aircraft.get('nucp'), 
      'seen_pos': aircraft.get('seen_pos'), 
      'altitude': aircraft.get('altitude'),
      'vert_rate': aircraft.get('vert_rate'),
      'track': aircraft.get('track'),
      'speed': aircraft.get('speed'),
      'messages': aircraft.get('messages'),
      'seen': aircraft.get('seen'),
      'rssi': aircraft.get('rssi'),
      'device_id': device_id,
      'timestamp': datetime.utcfromtimestamp(float(message_now)).isoformat()
    }

    result_json = json.dumps(result)
    result_hash = hashlib.sha512(result_json.encode('utf-8')).hexdigest()
    unique_id = f'{message_now}_{result_hash}'

    result['created_at'] = datetime.now().isoformat()
    return (unique_id, result)

  return zip( *map( copy_data, aircrafts ) )