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



database_name = GLib.get_tmp_dir() + "/test.db"

create_table = False
LongFast_channel_id = '399df22f29297e5dd9b23d8ddc229bb6e64f2d05365b5a478cf6527dc302652c'

class MsgDirection(Enum):
    In = 0
    Out = 1

def add_received_message_to_database(packet, interface, short_name, long_name, channel_id):
    con = sqlite3.connect(database_name)
    cur = con.cursor()
    new_message = []

    #text_messages(msg_id, from_id, from_short_name, from_long_name, to_id, direction, text, time, delivered, channel_id)")

    #msg_id
    new_message.append(packet["id"])
    #from_id
    # We only do the int version since we find nodes by this int id
    new_message.append(packet["from"])
    #from_short_name
    new_message.append(short_name)
    #from_short_name
    new_message.append(long_name)
    #to_id
    new_message.append(packet["to"])
    #direction
    new_message.append(MsgDirection.In.value)
    #Text
    if packet.get("decoded", {}).get("text"):
        new_message.append(packet["decoded"]["text"])
    else:
        new_message.append("no_text")
    #time
    if 'rxTime' in packet:
        new_message.append(packet["rxTime"])
        print(packet["rxTime"])
    else:
        new_message.append(0)
    #delivered
    new_message.append(False)
    #channel_Title
    new_message.append(channel_id)

#    print(new_message)

    cur.execute("INSERT INTO text_messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", new_message)
    con.commit()

    for row in cur.execute("SELECT * FROM text_messages ORDER BY time"):
        print(row)
    cur.close()
    con.close()

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

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

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

def onReceive(packet, interface):
    # Print all packets
    if not 'decoded' in packet:
        return

    if not packet['decoded'].get('portnum') == 'TEXT_MESSAGE_APP':
        return

    add_received_message_to_database(packet, interface, "B1", "Meshtastic 1234", LongFast_channel_id)

if not os.path.exists(database_name):
    create_table = True

""" If the database didn't exist, you need to make the table"""
if create_table:
    con = sqlite3.connect(database_name)
    cur = con.cursor()
    cur.execute("CREATE TABLE text_messages(msg_id, from_id, from_short_name, from_long_name, to_id, direction, text, time, delivered, channel_title)")
    con.commit()
    cur.close()
    con.close()

# 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()

while True:
    time.sleep(1)
