﻿from tkinter import *
import socket
import json
import time
import threading
import os

def getHour():
    minute = time.localtime()[4]
    minute=str(minute)
    if len(minute)==1:
        minute = '0'+minute
    heure = ' le '+str(time.localtime()[2])+'/'+str(time.localtime()[1])+'/'+str(time.localtime()[0])+' à '+str(time.localtime()[3])+'h'+minute
    return heure

def recive():
    while True:
        global reponse1
        global reponse
        reponse1 = client.recv(255)
        reponse1 = reponse1.decode()
        reponse = json.loads(reponse1)
        aff=reponse["nom"]+getHour()+" : "+reponse["message"]
        print(aff)



def send(text):
    heure = getHour()
    txtVal.set('')
    u=json.dumps({"nom" : nom,"heure":heure,"message":text})
    nomfichier=str(time.time())[:-4]
    fichier=open("messages_cache_cli/"+nomfichier,"w")
    fichier.write(u)
    fichier.close()
    global y
    y=json.loads(u)
    reponse=y["nom"]+heure+" : "+y["message"]
    print(reponse)
    client.send(u.encode())


os.makedirs("messages_cache_cli", exist_ok=True)
#adresseIP = "localhost" # Ici, le poste slocal
port = 50000    # Se connecter sur le port 50000
global client
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((adresseIP, port))
print("Connecté au serveur")
reponse=""
nom=input('')
fenetre = Tk()

txtVal = StringVar()
label = Label(fenetre, textvariable=txtVal).pack()
entree = Entry(fenetre, textvariable=txtVal, width=30)
entree.bind('<Return>', lambda x: send(txtVal.get()))
entree.pack()

label = Label(fenetre, text="Client")
label.pack()

bouton=Button(fenetre, text="Envoyer",command=lambda: send(txtVal.get()))
bouton.pack()


rec = threading.Thread(target=recive, args=())
rec.start()
fenetre.mainloop()

print("Connexion fermée")
client.close()
