#!/usr/bin/python2
# This file is part of SSHconf.
#
#    SSHconf is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    SSHconf is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with SSHconf.  If not, see <http://www.gnu.org/licenses/>.
#
# Author: Frank "ancho" Becker 
#
# Copyright 2010 Frank Becker <ancho@gmx.net>
'''
Created on 16.01.2010

@author: frank
'''
import logging
from PyQt4 import QtCore


class ProcessManager:
    '''
    A ProcessManager keeps an eye on running QProccess instances.
    '''

    
    def __init__(self, parent, eventhandler):
        '''
        Constructs a ProcessManager object with the given parent
        
        @param parent: A QObject parent
        @param eventhandler: An event handler implementing the method do_process_finished(proc,retval)
        '''
        self.processList = []
        self.parent = parent
        self.eventhandler = eventhandler
        self.log    = logging.getLogger("ProcessManager")
    
    def new(self, cmd):
        '''
        * create and add a QProcess to the manager list.
        * connects the finished SIGNAL to an event SLOT.
        * starts the process
        '''
        proc = QtCore.QProcess(self.parent)
        callback = lambda retval: self.eventhandler.do_process_finished(proc, retval)
        proc.finished.connect( callback )
        proc.error.connect( self.error )
        proc.start(cmd)
        self.processList.append(proc)
        self.log.info("Added new Process with Command: " + str(cmd) + " PID:" + str( proc.pid() ) )
        self.log.debug( str(self) )
    
    def error(self, error):
        self.log( error )
        
    def del_proc(self, proc):
        self.log.info("Delete Process")
        proc.close()
        self.processList.remove(proc)
        self.log.debug( str(self) )
        
    def __str__(self):
        line = '{0:10} {1:10}\n' 
        ret = "\n" + line.format("PID","STATE")
        
        for proc in self.processList:
            ret += line.format( str(proc.pid()), proc.state() )
        
        return ret
