import sys
import socket
Param = sys.argv[1:]

XbmcMonitor = None

def sleep():
    global XbmcMonitor

    if not XbmcMonitor:
        import xbmc
        XbmcMonitor = xbmc.Monitor()

    if XbmcMonitor.waitForAbort(0.1):
        return True

    return False

Argv = ';'.join(["service"] + Param)
DataSend = f"EVENT {Argv}".encode('utf-8')
Abort = False

for _ in range(60):  # 60 seconds timeout
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        sock.settimeout(0.1)
        sock.connect(('127.0.0.1', 57342))
        sock.send(DataSend)

        while True:
            try:
                sock.recv(1024)
                sock.close()
                break
            except TimeoutError:
                if sleep():
                    Abort = True
                    break
            except Exception as error:
                if str(error).find("timed out") != -1 or str(error).find("timeout") != -1: # workaround when TimeoutError not raised
                    if sleep():
                        Abort = True
                        break
                else:
                    break

        if Abort:
            break
    except:
        if sleep():
            break
