from math import isnan
from vts import clock_get

def fix_type_to_soultion_type(fix_type,flags):
    if (fix_type == 0x07):
        return  4
    elif (fix_type == 0x06):
        return 3
    elif (flags & 0x0020):
        return 2
    elif (flags & 0x0010):
        return 1
    else:
        return 0

class pyVBO():
    def __init__(self):
        self.LEAP_SEC = 18
        self.VBO_Index = 0
        #self.log = None
        self.unit_info = None
        self.Heading = 000000

    def header(self,unit,Channels = None):
        self.unit_info = unit
        now = clock_get()

        while True:
            try:
                log = open ("\VBOX{:02d}.vbo".format(self.VBO_Index) , "r")
                log.close()
            except:
                log = open ("\VBOX{:02d}.vbo".format(self.VBO_Index) , "w")
                break
            else:
                self.VBO_Index += 1

        log.write("File created on {:02}/{:02}/{:04}".format(now['day of month'],now['month'],now['year']))
        log.write(" @ {:02}:{:02}:{:02}".format(now['hours'],now['minutes'],now['seconds']))
        log.write("\n[header]\n")
        log.write("satellites\n")
        log.write("time\n")
        log.write("latitude\n")
        log.write("longitude\n")
        log.write("velocity kmh\n")
        log.write("heading\n")
        log.write("height\n")
        log.write("solution type\n")
        if Channels:
            for channel in Channels:
                log.write(channel["Name"] + "\n")

        if Channels:
            log.write("\n[channel units]\n")
            for channel in Channels:
                log.write(channel["Units"] + "\n")

        log.write("\n[comments]\n")
        log.write("Type : \n")
        log.write("Serial : {:06} \n".format(unit['Serial Number']))
        log.write("Frimware : {} {} {}\n".format(unit['Firmware Version'],unit['Firmware Date'],unit['Firmware Time']))
        log.write("Application : Python Logging\n")
        log.write("GNSS Engine : Something\n")
        log.write("GPS Time offset by -18 seconds\n")
        log.write("Log Rate (Hz) : 10.00\n")

        log.write("\n[column names]\n")
        log.write("sats time lat long velocity heading height solution_type ")
        if Channels:
            for channel in Channels:
                log.write(channel["Column"] + " ")
        log.write("\n\n[data]\n")
        log.close()


    def line(self,sam, data = None):
        log = open ("\VBOX{:02d}.vbo".format(self.VBO_Index) , "a")
        log.write('{:03d} '.format(int(sam.sats_used))) # Sat count
        log.write("{:02}{:02}{:02}.{:02} ".format(
            int(((sam.tod_ms/1000)-self.LEAP_SEC)/60/60) % 60,
            int(((sam.tod_ms/1000)-self.LEAP_SEC)/60) % 60,
            int((sam.tod_ms/1000)-self.LEAP_SEC) % 60,
            int((sam.tod_ms % 1000)/10)
        )) # time
        log.write('{:+011.5f} '.format(sam.lat_minE5/100000.0)) # latitude
        log.write('{:+012.5f} '.format(-sam.lng_minE5/100000.0)) # longitude+
        log.write('{:07.3f} '.format(sam.speed_gnd_mps*3.6)) # velocity
        if not isnan(sam.heading_deg):
            self.Heading = sam.heading_deg
        log.write('{:07.3f} '.format(self.Heading)) # heading
        log.write('{:+08.2f} '.format(sam.alt_msl_m)) # height
        log.write('{:02} '.format(fix_type_to_soultion_type(sam.fix_type,sam.flags))) # soultion type
        if data:
            for d in data:
                log.write(d["text"].format(d["number"]))
        log.write("\n")
        log.close()
