import meshtastic.serial_interface
from pubsub import pub
from meshtastic.protobuf import mesh_pb2, storeforward_pb2, paxcount_pb2
from meshtastic import BROADCAST_NUM
import time
import sys
import signal
import sqlite3
import os
from enum import Enum
from gi.repository import GLib
from datetime import datetime, timezone

meshtastic_config_dir = GLib.get_user_config_dir() + '/gtk_meshtastic_client'
version = 0

LongFast_channel_id = '399df22f29297e5dd9b23d8ddc229bb6e64f2d05365b5a478cf6527dc302652c'
limit = 3
offset = 0

def idToHex(nodeId):
    return '!' + hex(nodeId)[2:]

def onDisconnection(interface):
    #there's no need to close a connection once disconnected
    print("Awknowledged disconnection")

def onConnection(interface):
    print("Awknowledged connection")

def onReceive(packet, interface):
    print("Got packet")


# You need to close any active connections if you exit
# If you don't, the interface will continue to be active
# and any stored messages will stay stored on the device
# and will be sent on the stale connection
def signal_handler(sig, frame):
    print("closing")
    interface.close()
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
pub.subscribe(onReceive, 'meshtastic.receive')
pub.subscribe(onDisconnection, 'meshtastic.connection.lost')
pub.subscribe(onConnection, 'meshtastic.connection.established')
interface = meshtastic.serial_interface.SerialInterface()

node_id = idToHex(interface.myInfo.my_node_num)
database_name = meshtastic_config_dir + '/' + node_id + '_messages_v' + str(version) + '.db'
print(database_name)

if not os.path.exists(database_name):
    print("Cannot Find database")
    interface.close()
    sys.exit(0)


con = sqlite3.connect(database_name)
cur = con.cursor()


#Order test messages by time
#for row in cur.execute("SELECT * FROM text_messages ORDER BY time"):
#    print(row)

#find number of entries
res = cur.execute("SELECT COUNT(*) FROM text_messages")
count_list = res.fetchone()
print(count_list[0])

"""
#Print all the rows in the test message table
for row in cur.execute("SELECT * FROM text_messages"):
    print(row)

#DESC orders by latest time
for row in cur.execute("SELECT * FROM text_messages ORDER BY time DESC"):
    print(row)

#Limit 3 entries
for row in cur.execute("SELECT * FROM text_messages ORDER BY time DESC LIMIT 3"):
    print(row)
    #Table text_messages(msg_id, from_id, from_short_name, from_long_name, to_id, direction, text, time, delivered, channel_title)
    #print Msg_id
    print(row[0])
    #print from_long_name
    print(row[3])

#Limit 3, but skip the first 3 entries (so if you previously did limit 3, this gets the next 3)
for row in cur.execute("SELECT * FROM text_messages ORDER BY time DESC LIMIT 3 OFFSET 3"):
    print(row)

#make channel_if, limit, and offset variables you can imclude
for row in cur.execute("SELECT * FROM text_messages WHERE channel_title = ? ORDER BY time DESC LIMIT ? OFFSET ?", (LongFast_channel_id, limit, offset, )):
    print(row)
"""

con.commit()
cur.close()
con.close()
interface.close()
sys.exit(0)


while True:
    time.sleep(1)
