"""This file contains all code to allow debugging of another process."""
from mremote import RemoteWrapperClient

class ProcessWrapper(RemoteWrapperClient):

    """This class wraps an MPdb instance to provide functionality for
    debugging processes.
    """
    def __init__(self, mpdb_object):
        RemoteWrapperClient.__init__(self, mpdb_object)
        self.cmdqueue = self.mpdb.cmdqueue
        self.debug_signal = None

    def do_detach(self, args):
        """ Detach a process or file previously attached.
        If a process, it is no longer traced, and it continues its 
        execution. If you were debugging a file, the file is closed and
        Pdb no longer accesses it.
        """
        raise KeyboardInterrupt

    def do_attach(self, addr):
        """ Attach to a process or file outside of Pdb.
This command attaches to another target, of the same type as your last
"target" command. The command may take as argument a process id or a
device file. For a process id, you must have permission to send the
process a signal, and it must have the same effective uid as the debugger.
When using "attach" with a process id, the debugger finds the
program running in the process, looking first in the current working
directory, or (if not found there) using the source file search path
(see the "directory" command).  You can also use the "file" command
to specify the program, and to load its symbol table.
"""
        if not self.target_addr:
            self.errmsg('No target address is set')
            return
        try:
            pid = int(addr)
        except ValueError:
            # no PID
            self.errmsg('You must specify a process ID to attach to.')
            return
        if not self.debug_signal:
            from signal import SIGUSR1
            self.debug_signal = SIGUSR1
        try:
            import os
            os.kill(pid, self.debug_signal)
        except OSError, err:
            self.errmsg(err)
            return

        # XXX this still needs removing
        import time
        time.sleep(1.0)
        
        self.do_target(self.target_addr)

