#!/usr/bin/env python3
"""Script for Tkinter GUI chat client."""
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import tkinter
import pyaes
import base64

def receive():
    """Handles receiving of messages."""
    while True:
        try:
            msg = client_socket.recv(BUFSIZ).decode("utf8")
            key = bytes("This_key_for_demo_purposes_only!","utf8")
            aes = pyaes.AESModeOfOperationCTR(key)
            t = base64.b64decode(msg)
            plain = aes.decrypt(t)
            msg_list.insert(tkinter.END, plain)
        except OSError:  # Possibly client has left the chat.
            break


def send(event=None):  # event is passed by binders.
    """Handles sending of messages."""
    msg = my_msg.get()
    my_msg.set("")  # Clears input field.
    key = bytes("This_key_for_demo_purposes_only!","utf8")
    aes = pyaes.AESModeOfOperationCTR(key)
    t = aes.encrypt(msg)
    client_socket.send(base64.b64encode(t))
    if msg == "{quit}":
        client_socket.close()
        top.quit()


def filesend(event=None):
    """Handles files sending"""
    msg = "{file}"
    key = bytes("This_key_for_demo_purposes_only!","utf8")
    aes = pyaes.AESModeOfOperationCTR(key)
    t = aes.encrypt(msg)
    client_socket.send(base64.b64encode(t))
    filetosend = my_msg.get()
    my_msg.set("")
    byte = open(filetosend).read()
    filetosend = "sent_" + filetosend
    filetosend = bytes(filetosend, "utf8")
    client_socket.send(base64.b64encode(filetosend))
    t = bytes(byte, "utf8")
    client_socket.send(base64.b64encode(t))
    sent = "You've sent a file to the server!"
    msg_list.insert(tkinter.END, sent)

def on_closing(event=None):
    """This function is to be called when the window is closed."""
    my_msg.set("{quit}")
    send()

top = tkinter.Tk()
top.title("ChatApp")

messages_frame = tkinter.Frame(top)
my_msg = tkinter.StringVar()  # For the messages to be sent.
my_msg.set("Type your messages here.")
scrollbar = tkinter.Scrollbar(messages_frame)  # To navigate through past messages.
# Following will contain the messages.
msg_list = tkinter.Listbox(messages_frame, height=15, width=50, yscrollcommand=scrollbar.set)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
msg_list.pack()
messages_frame.pack()

entry_field = tkinter.Entry(top, textvariable=my_msg)
entry_field.bind("<Return>", send)
entry_field.pack()
v = tkinter.IntVar()
v.set(0)
encryption = [
    ("AES",1)
]

def ShowChoice():
    encryptval = int(v.get())
    
for val, encrypt in enumerate(encryption):
    tkinter.Radiobutton(top, 
                  text=encrypt,
                  padx = 20, 
                  variable=v, 
                  command=ShowChoice,
                  value=val).pack(anchor=tkinter.W)

send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()
send_button = tkinter.Button(top, text="File", command=filesend)
send_button.pack()

top.protocol("WM_DELETE_WINDOW", on_closing)

#----Now comes the sockets part----
HOST = input('Enter host: ')
PORT = input('Enter port: ')

if not PORT:
    PORT = 33000
else:
    PORT = int(PORT)

BUFSIZ = 4096
ADDR = (HOST, PORT)

client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)

receive_thread = Thread(target=receive)
receive_thread.start()
tkinter.mainloop() # Starts GUI execution.
