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

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

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

def onConnection(interface):
    print("Awknowledged connection")
    index = 0 #primary channel
    #publicKey = "MA==" #"MA==" is the default, indicating there is no public key
    # send_address = 2733239644
    # publicKey = "gQ5GJwFP50lqwz09yRt5GemztnjKkkyPSg2qFvUNvHI="

    noKey = True
    # It looks like you don't need the PKIKey to end the message.

    print(idToHex(send_address))

    if publicKey == "MA==":
        text = "send test Data no encryption"
        print("No encryption")
        # packet = interface.sendText(text=text, wantAck=True, destinationId=send_address)
        interface.sendData(
            data=text.encode("utf-8"),
            destinationId=send_address,
            portNum = portnums_pb2.PortNum.TEXT_MESSAGE_APP,
            wantAck=True,
            channelIndex = 0)

    else:
        if not noKey:
            print("Encrypted with key")
            text = "send test Data encrypted"
            interface.sendData(
                data=text.encode("utf-8"),
                destinationId=send_address,
                portNum = portnums_pb2.PortNum.TEXT_MESSAGE_APP,
                pkiEncrypted=True,
                publicKey=base64.b64decode(publicKey),
                wantAck=True,
                channelIndex = 0)
        else:
            print("Encrypted dont try with key")
            text = "send test Data encrypted no key"
            interface.sendData(
                data=text.encode("utf-8"),
                destinationId=send_address,
                portNum = portnums_pb2.PortNum.TEXT_MESSAGE_APP,
                pkiEncrypted=True,
                wantAck=True,
                channelIndex = 0)


def onReceive(packet, interface):
    if 'decoded' in packet:
        if packet['decoded'].get('portnum') == 'TEXT_MESSAGE_APP':
            print("Received Message")
            print(packet["decoded"]["text"])


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


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