import sqlite3
import pandas as pd
import matplotlib
from pylab import *
import numpy as np
import mutils as m  

systemLUT = { 0:'GPS',
            1:'SBAS',
            2:'GLONASS',
            3:'Galileo',
            4:'QZSS',
            9:'NavIC',
            10:'BeiDou'} 

# Load the database:
# open read only - we don't attempt to write to it in this script, set read only 
# to avoid future updates introducing accidental write bugs
db = sqlite3.connect('file:trackData.db?mode=ro', uri=True)

df = pd.read_sql_query('SELECT * FROM data ORDER BY year, month, day, hour, freq, track, elMask, sn', db)
# Convert the year, month, day, and hour columns to a single datetime column and use this as the index
df['datetime'] = pd.to_datetime(df[['year', 'month', 'day', 'hour']])
df = df.set_index('datetime')

# get a unique list of serial numbers
snList = df.sn.unique()

# get a unit list of freq, track, sat_type combinations
ftList = df[['freq', 'track', 'sat_type']].drop_duplicates()

for dataType in ['epochs','slips']:
    # loop around for each of the freq, track, sat_type combinations
    for ft in ftList.itertuples():
        # get the data for this freq, track, sat_type combination
        df2 = df[(df.freq == ft.freq) & (df.track == ft.track) & (df.sat_type == ft.sat_type) & (df.elMask == 10)]
        # loop around for each of the serial numbers

        fig, ax = subplots(1,1)
        for sn in snList:
            # get the data for this serial number
            df3 = df2[df2.sn == sn]
            # if there is data for this serial number, print it out
            if len(df3) > 0:
                date_strings = df3.index.strftime('%Y-%m-%d %H:%M:%S')
                # plot the data with a marker and line, and label it with the serial number
                ax.plot(date_strings, df3[dataType], marker='o', linestyle='-', label=sn)
                #print(f"\n{ft.freq} {ft.track} {ft.sat_type} {sn}")
                #print(df3)

        
        ax.legend(fontsize=6)
        typeStr = m.get_sub_type(ft.sat_type,ft.freq,ft.track).fullstr
        if(dataType == 'epochs'):
            ax.set_title('Epochs: ' + typeStr + ' > 10 degrees')
        else:
            ax.set_title('Slips: ' + typeStr + ' > 10 degrees')
        
        ax.set_ylabel('Number of ' + dataType)
        ax.set_xlabel('Date/Time')

        
        if(len(date_strings) <= 20):
            delta = 1
        elif(len(date_strings) <= 40):
            delta = 2
        else:
            delta = round(len(date_strings)/20)
        
        ax.set_xticks(date_strings[::delta])
        ax.tick_params(axis='x', labelsize=6)
        ax.tick_params(axis='y', labelsize=6)
        ax.grid(True)
        
        xticks(rotation=45)
        tight_layout()
        filename = typeStr.replace(' ','-') + '-' + dataType + '-10Deg.png'
        savefig(filename,dpi=600)
        close()

print('Finished')
