import asyncio
import asyncio.subprocess as subprocess
import signal
import os


class Runner():
    lock = asyncio.Lock()
    running = False
    running_type = ''
    proc = None

    async def run_robot(self, use_mock=False) -> bool:
        async with self.lock:
            if self.running:
                return False
            if use_mock == False:
                cmd = ["ros2", "launch", "toid_navigation", "main.py", f"use_mock:={use_mock}"]
            else:
                cmd = ["ros2", "launch", "toid_navigation", "main.py", f"use_mock:={use_mock}"]
            self.proc = await subprocess.create_subprocess_exec(
                *cmd,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                preexec_fn=os.setsid
            )
            self.running = True
            return True

    async def stop_robot(self):
        async with self.lock:
            if not self.running:
                return False

            os.killpg(os.getpgid(self.proc.pid), signal.SIGINT)
            try:
                await asyncio.wait_for(self.proc.wait(), timeout=8)
            except asyncio.TimeoutError:
                os.killpg(os.getpgid(self.proc.pid), signal.SIGKILL)
            self.running = False
            await self.proc.wait()
            return True

    def status(self):
            return self.running

main_runner = Runner()