#!/usr/bin/python3

import os
import json
import sqlite3
import requests
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.style as style

def Checkthedatabase():
  ## Some sanity for the database
  # check if btc_timeseries.db database file exists
  if not os.path.exists("btc_timeseries.db"):
    db = sqlite3.connect("btc_timeseries.db")
    db.execute("CREATE TABLE timeseries (timestamp INTEGER, value REAL)")
    db.commit()
    db.close()
  
  db = sqlite3.connect("btc_timeseries.db")
  
  # Check if the table exists
  table_exists = False
  cursor = db.execute("PRAGMA table_info(timeseries)")
  for row in cursor:
    table_exists = True
  
  # Create the table if it doesn't exist
  if not table_exists:
    db.execute("CREATE TABLE timeseries (timestamp INTEGER, value REAL)")
    db.commit()
  
def Getdata():
  #fetch the price data
  payload = {'symbol': 'BTCUSDT'}
  response = requests.get('https://api.binance.com/api/v3/avgPrice', params=payload)
  
  #get the usd_value
  json_data = response.json()
  usd_value = json_data['price']
  
  ### Insert the USD value into the database
  db.execute("INSERT INTO timeseries (timestamp, value) VALUES (datetime('now'), ?)", (usd_value,))
  
  ## Save the changes to the database
  db.commit()
  #print(db.execute("SELECT * FROM timeseries"))
  
#update the graph
def Updategraph(num):
  cursor.execute("SELECT timestamp, value FROM timeseries WHERE timestamp > datetime('now', '-10 second')")
  stuff = cursor.fetchall()

  timestamps = [row[0] for row in stuff]
  values = [row[1] for row in stuff]

  line.set_data(timestamps, values)
  ax.relim()
  ax.autoscale_view()
  Getdata()

Checkthedatabase()

db = sqlite3.connect("btc_timeseries.db")
Getdata()

##some styling for the plot
style.use('dark_background')

colors = {
  'figure.facecolor': '#222222',
  'axes.facecolor': '#222222',
  'axes.edgecolor': '#FFFFFF',
  'axes.labelcolor': '#FFFFFF',
  'grid.color': '#444444',
  'grid.linestyle': 'dotted',
  'lines.color': '#FFFFFF'
}
matplotlib.rcParams.update(colors)

# Create a figure and axes for the plot
fig, ax = plt.subplots()

#query database for the data
cursor = db.execute("SELECT timestamp, value FROM timeseries")

stuff = cursor.fetchall()
# Extract the timestamp and value columns from the query result
timestamps = [row[0] for row in stuff]
values = [row[1] for row in stuff]

# Create a line plot using the time series data
line, = ax.plot(timestamps, values)
plt.plot(timestamps, values)

# Create an animation using the update function
ani = animation.FuncAnimation(fig, Updategraph, interval=60000)

# Show the plot
plt.show()

db.close()
exit(0)
