from socket import *
from tkinter import *
import threading

def sendMessage(): #two send message functions because return type requires (event) parameters
    message = e.get() # -which is not compatible with the first sendMessage call in send button
    s.send(message.encode())

def sendMessageEnter(event):
    message = e.get()
    s.send(message.encode())
    input_user.set('')

def receiveMessage(): #try/except doesn't fix crash here
    while True:
        reply = s.recv(1024)
        reply = reply.decode()
        print("Recieved ", repr(reply)) #just to test outside the interface
        messages.insert(INSERT, '%s\n' % reply)

try:
    s = socket(AF_INET, SOCK_STREAM)
    s.connect(("82.27.169.93", 1337))
except:
    print('Connection failed.')

#Set-up of interface
root = Tk()
root.title("Psst Chat Client")
root.geometry("500x400")
tk_rgb = '#212121'
tk_rgb2 = '#424242'
tk_rgb3 = '#E0E0E0'
root.configure(background=tk_rgb)

#frame for send button
f = Frame(root, height=32, width=100)
f.pack_propagate(0) # don't shrink
f.place(x=395,y=362)
#send button
b = Button(f, text="Send",command=sendMessage, bg=tk_rgb2, fg='white', font=("Helvetica", 9))
b.pack(fill=BOTH, expand=1)
#frame for entry text box
f1 = Frame(root, height=32, width=400)
f1.pack_propagate(0) # don't shrink
f1.place(x=5,y=362)
#entry text box
input_user = StringVar()
e = Entry(f1, bg=tk_rgb3, text=input_user)
e.pack(fill=BOTH, expand=1)
e.delete(0, END)
e.bind("<Return>", sendMessageEnter)

#frame for text window?
t = Frame(root, height=300, width=395)
t.place(x=10,y=10)
#actual text box
messages = Text(t, bg=tk_rgb3)
messages.place(x=0,y=0)

#Threading
newThread = threading.Thread(target=receiveMessage)
newThread.start()

root.mainloop()
