import subprocess
import os
import threading
import platform
import ctypes

class ServiceManager:
    @staticmethod
    def get_status(svc_id):
        os_type = platform.system()
        try:
            if os_type == "Linux":
                result = subprocess.run(['systemctl', 'is-active', '--quiet', svc_id])
                return "active" if result.returncode == 0 else "inactive"
            elif os_type == "Windows":
                result = subprocess.run(['sc', 'query', svc_id], capture_output=True, text=True)
                if "RUNNING" in result.stdout: return "active"
                if "STOPPED" in result.stdout: return "inactive"
                if "SERVICE_NOT_FOUND" in result.stdout: return "not_installed"
                return "unknown"
            elif os_type == "Darwin":
                result = subprocess.run(['launchctl', 'list', svc_id], capture_output=True, text=True)
                return "active" if result.returncode == 0 else "inactive"
        except Exception:
            return "unknown"
        return "unknown"

    @staticmethod
    def run_command(svc_id, action, callback=None):
        os_type = platform.system()
        try:
            if os_type == "Linux":
                cmd = ['pkexec', 'systemctl', action, svc_id]
                process = subprocess.Popen(cmd)
                if callback:
                    threading.Thread(target=ServiceManager._wait_for_process, args=(process, callback), daemon=True).start()
            elif os_type == "Windows":
                verb = "runas"
                action_cmd = "start" if action == "start" else "stop"
                try:
                    ctypes.windll.shell32.ShellExecuteW(None, verb, "net.exe", f"{action_cmd} {svc_id}", None, 1)
                    if callback: callback(True)
                except:
                    if callback: callback(False)
            elif os_type == "Darwin":
                cmd = ['sudo', 'launchctl', 'load' if action == 'start' else 'unload', svc_id]
                process = subprocess.Popen(cmd)
                if callback:
                    threading.Thread(target=ServiceManager._wait_for_process, args=(process, callback), daemon=True).start()
            return True
        except Exception as e:
            print(f"Error: {e}")
            if callback: callback(False)
            return False

    @staticmethod
    def _wait_for_process(process, callback):
        process.wait()
        callback(process.returncode == 0)
