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

def rcv_message(client, userdata, msg):
    msg_list.insert(tk.END, msg.payload.decode())
    msg_list.yview_moveto(1) # To move the Listbox in the last inserted entry
 
def snd_message(event=None): # to ensure a defaul value of variable event
    msg = my_msg.get()
    my_msg.set("")
    if len(msg.strip()) <= 0: # Whitespaces at the begging and end are removed
        return
    if msg == ":q":
        on_closing()
    else:
        msg = f"{CLIENT_ID}: {msg}"
        client.publish(TOPIC, 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 = "Pippo"
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() # Differently from loop_forever() the control returns to the main program
win.mainloop()
