import os
import subprocess
import time
import sys

from ..utils import isMac, isWindows

from ..utils_debug import debug_err

from ..utils_web_project import getOpenUrlCommand

from ..external_process import exec_command, stopExternalProcesses


__startedServer: subprocess.Popen = None
__startedServerDirectory: str = None

def hasStartedServer():
    return __startedServer is not None

# start https server in directory with blender
# python -m http.server 8000 --bind
def startHttpServer(directory):
    global __startedServer, __startedServerDirectory
    if __startedServerDirectory == directory:
        print("Server already started in", directory)
        openHttpServerInBrowser()
        return

    print("Stopping server")
    stopHttpServer()

    print("Starting server in", directory)
    os.chdir(directory)
    try:
        pathToBlenderPython = sys.executable
        if isWindows():
            pathToBlenderPython = "\"" + pathToBlenderPython + "\""
        __startedServer = exec_command(pathToBlenderPython + " -m http.server 8000", directory)
        print("Server started")
        openHttpServerInBrowser()
        __startedServerDirectory = directory
    except Exception as e:
        debug_err("Failed starting server in " + directory, e)

def stopHttpServer():
    global __startedServer, __startedServerDirectory
    if __startedServer is not None:
        print("Stopping server")
        try:
            __startedServer.send_signal(subprocess.signal.CTRL_C_EVENT)
        except:
            if __startedServer.poll() is None:
                __startedServer.terminate()
            try:
                __startedServer.kill()
            except:
                pass
        finally:
            __startedServer = None
    __startedServerDirectory = None

def openHttpServerInBrowser():
    timeInMillis = int(round(time.time() * 1000))
    openUrlCmd = getOpenUrlCommand("http://localhost:8000?v=" + str(timeInMillis))
    exec_command(openUrlCmd)


def register():
    pass

def unregister():
    stopHttpServer()
    pass