#################################
# Launch vis.exe
#################################
import http.client
import os
import re
import subprocess

try:
    import psutil
except Exception:  # pragma: no cover - optional dependency
    psutil = None

# Set the path to vis.exe in the current directory of the current script
current_directory = os.path.dirname(os.path.abspath(__file__))
vis_exe_path = os.path.join(current_directory, "vis", "vis.exe")


# Check if vis.exe is running
def is_vis_running():
    if psutil is None:
        return False
    for proc in psutil.process_iter(["name"]):
        if proc.info.get("name") == "vis.exe":
            return True
    return False


# Send network message
def HTTPPOST(ip, phg):
    headers = {
        "Connection": "keep-alive",
        "Content-Type": "text/plain",
    }
    conn = http.client.HTTPConnection(f"{ip}:5088")
    conn.request("POST", "/phg", phg, headers)
    conn.getresponse()
    conn.close()


# Call HTTPPOST function to send network message
def vis(phg):
    if not is_vis_running():
        subprocess.Popen(vis_exe_path)
    return HTTPPOST("127.0.0.1", phg.encode())


# Build image request payload with parameters
def _build_img_request(phg, filename):
    if "|||" not in phg:
        return f"{phg}|||file={filename}"
    code, params = phg.split("|||", 1)
    params = params.strip()
    if "file=" in params:
        params = re.sub(r"file=\\S+", f"file={filename}", params)
    else:
        params = f"{params} file={filename}".strip()
    return f"{code}|||{params}"


# Send image request
def HTTPPOST_IMG(ip, phg, filename="shot.png"):
    headers = {
        "Connection": "keep-alive",
        "Content-Type": "text/plain",
    }
    request_body = _build_img_request(phg, filename)

    conn = http.client.HTTPConnection(f"{ip}:5088")
    conn.request("POST", "/phg_img", request_body, headers)
    conn.getresponse()
    conn.close()


# Call HTTPPOST function to send network message
def image(phg, filename="shot.png"):
    if not is_vis_running():
        subprocess.Popen(vis_exe_path)
    return HTTPPOST_IMG("127.0.0.1", phg.encode("utf-8").decode("utf-8"), filename)
