'''
  ____   ___  _     _ _       
 / ___| / _ \| |   (_) |_ ___ 
 \___ \| | | | |   | | __/ _ \
  ___) | |_| | |___| | ||  __/
 |____/ \__\_\_____|_|\__\___|
                              
Script to read data from a sqlite database using start date and end date

/usr/bin/python3 /var/www/nebuleair_pro_4g/sqlite/read_select_date.py data_NPM 2025-02-09 2025-02-11

Available table are
data_NPM
data_NPM_5channels
data_BME280
data_envea
timestamp_table

'''

import sqlite3
import sys

parameter = sys.argv[1:]  # Exclude the script name
#print("Parameters received:")
table_name=parameter[0]
start_date=parameter[1]
end_date=parameter[2]

# Convert to full timestamp range
start_timestamp = f"{start_date} 00:00:00"
end_timestamp = f"{end_date} 23:59:59"

# Connect to the SQLite database
conn = sqlite3.connect("/var/www/nebuleair_pro_4g/sqlite/sensors.db")
cursor = conn.cursor()

# Retrieve the last 10 sensor readings
#cursor.execute("SELECT * FROM data_NPM ORDER BY timestamp DESC LIMIT 10")
#cursor.execute("SELECT * FROM data_BME280 ORDER BY timestamp DESC LIMIT 10")
#cursor.execute("SELECT * FROM timestamp_table")
if table_name == "timestamp_table":
  cursor.execute("SELECT * FROM timestamp_table")

else:
    query = f"SELECT * FROM {table_name} WHERE timestamp BETWEEN ? AND ? ORDER BY timestamp ASC"
    cursor.execute(query, (start_timestamp, end_timestamp))


rows = cursor.fetchall()
rows.reverse()  # Reverse the order in Python (to get ascending order)


# Display the results
for row in rows:
    print(row)

# Close the database connection
conn.close()
