import threading
import subprocess
import queue
import sys
class ServerThread(threading.Thread):
  def __init__(self, scene_dir, ip, port, msg_queue, callback):
    super().__init__()
    self.callback = callback
    self.ip = ip
    self.port = str(port)
    self.msg_queue = msg_queue
    self.scene_dir = scene_dir
    self.stop_event = threading.Event()

  def run(self):
    # Path to your JavaScript server script
    
    server_script = "modules/server/server-win.exe"

    if getattr(sys, 'frozen', False):
      server_script = "_internal/" + server_script

    grab_ip = True
    with subprocess.Popen([server_script, self.scene_dir, self.port], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
      self.process = p
      if self.stop_event.is_set():
        return
      for line in p.stdout:
        if self.stop_event.is_set():
          break
        self.msg_queue.put(line.decode().strip())
    self.stop()
  
  def stop(self):
    self.stop_event.set()
    if self.process:
      self.process.terminate()
      self.process.wait() 
    self.callback()


class UploadServer():
  def __init__(self, scene_dir : str, ip : str, port : str) -> None:
    msg_queue = queue.Queue()
    self.server_thread = ServerThread(scene_dir, ip, port, msg_queue, self.stop_server)
    self.server_thread.start()
    self.running = True 
  
  def terminate_server(self):
    self.server_thread.stop()

  def stop_server(self):
    self.running = False

  def is_running(self):
    return self.running