from typing import TYPE_CHECKING

from rpcclient.core.structs.consts import SIGTERM
from rpcclient.exceptions import BadReturnValueError

if TYPE_CHECKING:
    from rpcclient.core.client import CoreClient


class Processes:
    def __init__(self, client: "CoreClient"):
        """
        process manager
        :param rpcclient.darwin_client.Client client: client
        """
        self._client = client

    def kill(self, pid: int, sig: int = SIGTERM):
        """Send a signal to a remote process."""
        if self._client.symbols.kill(pid, sig) != 0:
            raise BadReturnValueError(f"kill({pid}, {sig}) failed ({self._client.last_error})")

    def waitpid(self, pid: int, flags: int = 0):
        """Wait for a remote process to change state and return status."""
        with self._client.safe_malloc(8) as stat_loc:
            err = self._client.symbols.waitpid(pid, stat_loc, flags).c_int64
            if err == -1:
                raise BadReturnValueError(f"waitpid(): returned {err} ({self._client.last_error})")
            return stat_loc[0]
