__author__ = 'Martin'
import numpy
from scipy.interpolate import InterpolatedUnivariateSpline
import sys
import time
import sqlite3
import pickle
from collections import defaultdict

def dict_factory(cursor, row):  # foe access to database with dick keys
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

interpolators = {}
rec_data = defaultdict(dict)
path_database = "C:\Users\Martin\Diplomka\Project_v1\gui\\test_data\\13-5-2016_10-47-2.db"
query = "SELECT * FROM GEN"

conn = sqlite3.connect(str(path_database))
conn.row_factory = dict_factory  # return dict when is query

with conn:
    cur = conn.cursor()
    cur.execute(query)
    rows = cur.fetchall()
    for row in rows:
        #rec_data[row["TOW"]][row["Sat"]] = row["TrPR"]
        rec_data[row["Sat"]][row["TOW"]] = row["TrPR"]

    for sat in rec_data.keys():
        value = rec_data[sat]
        list_tow = sorted(value.keys())
        list_psr = []
        for tow in list_tow:
            list_psr.append(value[tow])

        interpolators[sat] = InterpolatedUnivariateSpline(list_tow, list_psr, k=3)

with open('entry.pickle', 'wb') as f:
    pickle.dump(interpolators, f)


print interpolators.keys()
"""
773500: {u'GPS27': 20283167.049, u'GPS1': 24414070.5769, u'GPS2': 24375352.7228, u'GPS3': 23540062.1775,
         u'GPS6': 21207585.2923, u'GPS31': 20579053.838, u'Galileo7': 23709764.07, u'Galileo5': 27005797.6996,
         u'Galileo8': 26967638.3142, u'GPS28': 22903317.1703, u'Galileo6': 23726903.7308,
         u'Galileo14': 24902692.0076, u'GPS11': 24012040.0079, u'Galileo13': 23269524.315, u'Galileo12': 25266361.1452},
3132800: {u'GPS27': 20272358.1851, u'GPS26': 25125993.8461, u'Galileo7': 24385013.0078, u'GPS3': 25072973.5529,
          u'GPS31': 21455975.6038, u'GPS6': 20349516.1275, u'GPS7': 24156959.2361, u'Galileo5': 25866574.2322,
          u'Galileo8': 28197990.6184, u'GPS28': 21987327.736, u'Galileo6': 23341994.1541,
          u'Galileo14': 25902859.4555, u'GPS11': 22834807.1359, u'Galileo11': 28141488.9957, u'Galileo13': 23337131.7437,
          u'Galileo12': 24339314.1931}
"""
#interpolators = []
#for sat in rec_data["Sat"]:
#     # kde x a y je list casu (TOW) a PR pro dany satelit