import concurrent.futures
import time
import socket
from queue import Queue
from threading import Thread

class TcpCheck(Thread):
    def __init__(self, hostname, wan_a, wan_b, timeout):
        super().__init__()
        self.hostname = hostname
        self.wan_a = wan_a
        self.wan_b = wan_b
        self.timeout = timeout
        self.queue = Queue()

    def run(self):
        try:
            with socket.create_connection((self.hostname, 80), timeout=self.timeout):
                self.queue.put(("Server up", True))
            elif self.hostname.startswith("PTH2", "PTH3"):
                ip = socket.gethostbyname(self.hostname)
                wan_ip = '.'.join(ip.split('.')[:-1] + ['10'])
                try:
                    with socket.create_connection((wan_ip, 23), timeout=self.timeout):
                        self.queue.put(("Server down", False)
                except (socket.timeout, ConnectionRefusedError, OSError):
                    self.queue.put(("WAN down", False)
            elif self.hostname.startswith(("PTH11", "PTH15")) or self.hostname.startswith(("169", "s")):
                for ip, port in [(self.wan_a, 23), (self.wan_b, 23)]:
                    if ip:
                        try:
                            with socket.create_connection((ip, port), timeout=self.timeout):
                                self.queue.put(("Server down", False)
                        except (socket.timeout, ConnectionRefusedError, OSError):
                            pass
                self.queue.put(("WAN down", False)
            else:
                self.queue.put(("Server down", False)
        except (socket.timeout, ConnectionRefusedError, OSError):
            self.queue.put(("Connection error", False)

def tcp_socket(hostname, wan_a=None, wan_b=None, timeout=2, max_retries=5):
    global prev_ping_time
    n = QTime.currentTime().toString("hh:mm:ss")
    inspect_status = ""
    if hostname.startswith("169.254.163.169"): 
        current_time = time.time()
        time_diff = current_time - prev_ping_time if prev_ping_time != 0 else 0
        print(f"{n} Ping Checked (Diff previous ping: {time_diff:.2f}s)")
        prev_ping_time = current_time

    # Check most common ports first
    for port in [80, 443, 22, 23, 3389]:
        try:
            if socket.create_connection((hostname, port), timeout=timeout):
                inspect_status = "Server up"
                #print(f"{n} Ping {hostname}")
                #if hostname.startswith("169"): print(f"{n} Ping PTH15067")
                return True, inspect_status
        except (socket.timeout, ConnectionRefusedError, OSError):
            continue  # Try the next port

    # Second Checking
    if hostname.startswith(("PTH2", "PTH3")):
        ip = socket.gethostbyname(hostname)
        wan_ip = '.'.join(ip.split('.')[:-1] + ['10'])
        try:
            with socket.create_connection((wan_ip, 23), timeout=timeout):
                inspect_status = "Server down"
                return False, inspect_status
        except (socket.timeout, ConnectionRefusedError, OSError):
            inspect_status = "WAN down"
            return False, inspect_status
    elif hostname.startswith(("PTH11", "PTH15")) or hostname.startswith(("169", "s")):
        for ip, port in [(wan_a, 23), (wan_b, 23)]:
            if ip:
                try:
                    with socket.create_connection((ip, port), timeout=timeout):
                        inspect_status = "Server down"
                        return False, inspect_status
                except (socket.timeout, ConnectionRefusedError, OSError):
                    pass
        inspect_status = "WAN down"
        return False, inspect_status
    else:
        inspect_status = "Server down"
        return False, inspect_status

    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        check_queue = Queue()
        for _ in range(max_retries):
            executor.submit(TcpCheck(hostname, wan_a, wan_b, timeout).start())
            while not check_queue.empty():
                result, success = check_queue.get()
                if success:
                    return result, "TcpCheck Finished"
        inspect_status = "TcpCheck Retries Exhausted"
    return False, inspect_status
อธิบายโดยละเอียด