#!/usr/bin/python3

import os, time
import json, math
import sqlite3
import requests
from datetime import datetime, timezone

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, mins INTEGER, source TEXT)")
    db.commit()
  
  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, mins INTEGER, source TEXT)")
    db.commit()
  
  db.close()

def Getdata():
  #fetch the price data
  source = 'http://api.binance.com/api/v3/avgPrice'
  payload = {'symbol': 'BTCUSDT'}
  response = requests.get(source, params=payload)
  
  #get the usd_value
  json_data = response.json()
  usd_value = json_data['price']
  mins = json_data['mins']
  
  ### Insert the USD value into the database
  db.execute("INSERT INTO timeseries (timestamp, value, mins, source) VALUES (datetime('now'), ?, ?, ?)", (usd_value, mins, source))
  
  ## Save the changes to the database
  db.commit()
  #print(db.execute("SELECT * FROM timeseries"))
  
def Calculatetimesince():
  cursor = db.execute("SELECT * FROM timeseries ORDER BY timestamp DESC LIMIT 1")
  stuff = cursor.fetchall()

  timestamp = stuff[0][0]
  mins = stuff[0][2]
  
  timenow = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
  dt1 = datetime.strptime(timenow, "%Y-%m-%d %H:%M:%S")
  dt2 = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
  delta = dt1 - dt2
  minutedelta = divmod(delta.total_seconds(), 60)
  minutessince = math.trunc(minutedelta[0])
  

  # if minutes since last run is larger than mins we should get new data
  print(minutessince, ' - ', mins)
  if minutessince <= mins:
    return 0
  else:
    return 1 

Checkthedatabase()

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

while True:
  # Check if it's time to run again
  mayberun = Calculatetimesince()
  # we go on 1
  print(datetime.now(), 'We go on 1, should we go:', mayberun)
  if mayberun == 1:
    Getdata()
  
  time.sleep(20)

db.close()
exit(0)
