import paho.mqtt.client as mqtt 
import tkinter as tk
import time
import json

def rcv_message(client, userdata, msg):
    rcv_msg = json.loads(msg.payload.decode())
    print(rcv_msg)
    if rcv_msg["message"].strip()[0] == "@":
        if rcv_msg["user"] == CLIENT_ID:
            print("Message to myself")
            pass
        elif not rcv_msg["message"].split()[0].strip() == f"@{CLIENT_ID}":
            print("Message addressed to other user")
            return
    msg_list.insert(tk.END, f"{rcv_msg['user']}: {rcv_msg['message']}")
    msg_list.yview_moveto(1)
 
def snd_message(event=None):
    msg = my_msg.get()
    my_msg.set("")
    if len(msg.strip()) <= 0:
        return
    if msg == ":q":
        on_closing()
    else:
        # msg = f"{CLIENT_ID}: {msg}"
        json_msg = {
            "user": CLIENT_ID,
            "message": msg,
            "timestamp": int(time.time()),
            "is_encrypted": False
        }
        client.publish(TOPIC, json.dumps(json_msg))
    
def on_closing(event=None):
    """This function is called when the window is closed."""
    client.loop_stop()
    win.quit()


BROKER = 'test.mosquitto.org'
TOPIC = 'unimib/chat'
CLIENT_ID = input('Enter client name: ')

client = mqtt.Client(CLIENT_ID)
client.on_message = rcv_message
client.connect(BROKER)
client.subscribe(TOPIC)

win = tk.Tk()
win.title(f"Chatter [{CLIENT_ID}]")

msg_list = tk.Listbox(win, height=15, width=50) # Sets the dimension of the vertical scrollbar
msg_list.pack()

my_msg = tk.StringVar()
my_msg.set("Your message here")

def clear_on_focus(event=None):
    my_msg.set("")

entry_field = tk.Entry(win, textvariable=my_msg)
entry_field.bind("<Return>", snd_message)
entry_field.bind("<FocusIn>", clear_on_focus)

send_button = tk.Button(win, text="Send", command=snd_message)

entry_field.pack()
send_button.pack()

win.protocol("WM_DELETE_WINDOW", on_closing)

client.loop_start()
tk.mainloop()
