from datetime import datetime
import pytz


def read_gpvtg(sentence, timestamp, do_print=False):
    """ Read and parse GPVTG message"""
    values = sentence.split('*')[0].split(',')
    result = {}

    # Linux timestamp
    try:
        result['linux_stamp'] = int(timestamp)
    except:
        result['linux_stamp'] = 0
    result['linux_date'] = datetime.fromtimestamp(result['linux_stamp'], tz=pytz.UTC)

    # True Track
    try:
        result['truetrack'] = float(values[1])
    except:
        result['truetrack'] = None

    # Magnetic Track
    try:
        result['magnetictrack'] = float(values[3])
    except:
        result['magnetictrack'] = None

    # Groundspeed, knots
    try:
        result['groundspeed_knots'] = float(values[5])
    except:
        result['groundspeed_knots'] = None

    # Groundspeed, km/h
    try:
        result['groundspeed_kmh'] = float(values[7])
    except:
        result['groundspeed_kmh'] = None

    if do_print:
        if result['truetrack'] is None and \
           result['magnetictrack'] is None and \
           result['groundspeed_knots'] is None and \
           result['groundspeed_kmh'] is None:
            pass
        else:
            print("Linux timestamp   :", result['linux_stamp'])
            print("Linux datetime    :", result['linux_date'])
            print("  True Track      :", result['truetrack'])
            print("  Magnetic Track  :", result['magnetictrack'])
            print("  Ground spd, knot:", result['groundspeed_knots'])
            print("  Ground spd, km/h:", result['groundspeed_kmh'])
            print("")

    return result