import socket
import tkinter as tk
import threading
import re


def on_validate(P):
    # Проверка на соответствие шаблону IP-адреса (допускаются промежуточные неполные значения)
    pattern = (
        r"^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){0,3}"
        r"(25[0-5]|2[0-4]\d|[01]?\d\d?)?$"
    )
    return re.match(pattern, P) is not None


class ServerConnectionApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Server Connection App")

        # GUI setup
        self.setup_gui()

        # Server connection
        self.client_socket = None

    def setup_gui(self):
        self.ip_label = tk.Label(self.root, text="IP Address:")
        self.ip_label.grid(row=0, column=0)

        self.ip_entry = tk.Entry(self.root)
        self.ip_entry.grid(row=0, column=1)
        self.ip_entry.insert(0, "127.0.0.1")  # Default IP address (localhost)

        self.port_label = tk.Label(self.root, text="Port:")
        self.port_label.grid(row=1, column=0)

        self.port_entry = tk.Entry(self.root)
        self.port_entry.grid(row=1, column=1)
        self.port_entry.insert(0, "12345")  # Default port

        self.connect_button = tk.Button(self.root, text="Connect", command=self.initiate_connection)
        self.connect_button.grid(row=2, column=0, columnspan=2)

        self.status_label = tk.Label(self.root, text="")
        self.status_label.grid(row=3, column=0, columnspan=2)

    def initiate_connection(self):
        ip = self.ip_entry.get()
        port = int(self.port_entry.get())

        # Create a thread to avoid blocking the GUI
        connection_thread = threading.Thread(target=self.connect_to_server, args=(ip, port))
        connection_thread.daemon = True
        connection_thread.start()

    def connect_to_server(self, ip, port):
        try:
            self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.client_socket.connect((ip, port))
            self.status_label.config(text="Connected successfully.")
            
            # Consume the data and print it to the console
            self.listen_to_server()
            
        except Exception as e:
            self.status_label.config(text=f"Connection failed: {e}")

    def listen_to_server(self):
        try:
            while True:
                data = self.client_socket.recv(1024)
                if data:
                    print("Received from server:", data.decode())
                else:
                    # Connection is closed
                    print("Server has closed the connection.")
                    self.client_socket.close()
                    break
        except Exception as e:
            print(f"Error while listening to the server: {e}")
            if self.client_socket:
                self.client_socket.close()

# Create the Tkinter window
root = tk.Tk()

# Create an instance of the app
app = ServerConnectionApp(root)

# Start the Tkinter main event loop
root.mainloop()