from datetime import datetime
import pytz


def read_gpgsa(sentence, timestamp, do_print=False):
    """ Read and parse GPGSA 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)

    # Fix selection
    try:
        result['fix_selection'] = str(values[1])
    except:
        result['fix_selection'] = None

    # Fix type
    try:
        result['fix_type'] = int(values[2])
    except:
        result['fix_type'] = None

    # Fix satellites
    try:
        result['fix_satellites'] = []
        for sat in range(3, 3+12):
            try:
                sat_no = int(values[sat])
                result['fix_satellites'].append(sat_no)
            except:
                pass
    except:
        result['fix_satellites'] = None

    # Satellite counts
    if result['fix_satellites'] is None:
        result['fix_sat_count'] = 0
    else:
        result['fix_sat_count'] = len(result['fix_satellites'])

    # PDOP
    try:
        result['pdop'] = float(values[15])
    except:
        result['pdop'] = None

    # HDOP
    try:
        result['hdop'] = float(values[16])
    except:
        result['hdop'] = None

    # VDOP
    try:
        result['vdop'] = float(values[17])
    except:
        result['vdop'] = None
    if do_print:
        print("Linux timestamp   :", result['linux_stamp'])
        print("Linux datetime    :", result['linux_date'])
        print("  Fix selection   :", result['fix_selection'])
        print("  Fix type        :", result['fix_type'])
        print("  Satellites count:", result['fix_sat_count'])
        print("  Fix satellites  :", end=" ")
        if result['fix_satellites'] is None:
            print("NONE")
        elif len(result['fix_satellites']) == 0:
            print("EMPTY")
        else:
            for sat in result['fix_satellites']:
                print(sat, end=" ")
            print()
        print("  PDOP            :", result['pdop'])
        print("  HDOP            :", result['hdop'])
        print("  VDOP            :", result['vdop'])
        print()

    return result