#!/usr/bin/env python
# coding=utf-8

##    Qemulator - a qemu gui written in python and GTK/Glade.
##    Copyright (C) 2006  rainer haage
##
##    This program 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 2
##    of the License, or (at your option) any later version.
##    
##    This program 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 this program; if not, write to the Free Software
##    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import threading
from threading import Thread
#import signal
import string
import os
import re
import time
import locale

encoding = locale.getpreferredencoding()
utf8conv = lambda x : unicode(x, encoding).encode('utf8')

class PtsMan(Thread):
    
    def __init__ (self, pts, command, return_func=None):
        Thread.__init__(self)
        self.stopall = False
        self.pts = pts
        self.command = command
        self.return_func = return_func
        self.outlist = []
        self.call = "echo " + self.command + " > " + self.pts

    def run(self): 
        #time.sleep(0.2)
        error = False
        runcom = self.run_command()
        if runcom != True:
            error = True
        if error != True:
            try:
                fo = open(self.pts,"r")
                #termencoding = fo.encoding
                #print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
                #print "The qemu console uses the following encoding: " + str(termencoding)
            except:
                #raise IOError, "Couldn't open pts device!"
                error = True
        if error != True:
            commandline = None
            self.outlist = []
            c = 0
            commandline = re.search(self.command, fo.readline())
            while commandline == None:
                #print "+++ fo state: " + str(fo)
                if self.stopall == True:
                    #print "*** fo state: " + str(fo)
                    fo.close() 
                    break
                try:
                    searchline =  fo.readline()
                    uniline = unicode(searchline, "iso8859-1")
                    outline = string.strip(uniline.encode('utf8', 'replace'))
                    commandline = re.search(self.command, outline)
                except:
                    print "could not read commandline from " + self.pts 
                if commandline != None:
                    if commandline.group() == self.command:
                        #print "commandline found in output: " + str(commandline.group())
                        break
                c = c+1
                time.sleep(0.1)
            #print "waiting done -- result: \n"
            if commandline == None:
                print "Error: command: " + self.command +  " could not launched"
                fo.close()
            
            else:
                #print "Start reading result..."
                stopper = None
                while os.path.exists(self.pts) and stopper == None and self.stopall != True:
                    if self.stopall == True:
                        #print "*** fo state: " + str(fo)
                        fo.close() 
                        break
                    outres =  fo.readline()
                    stopper = re.match("\(qemu\)", outres)  
                    if stopper != None:
                        fo.close()
                        break
                    if string.strip(outres) != "":
                        apstr = unicode(outres, "iso8859-1")
                        apstr = string.strip(apstr.encode('utf8', 'replace'))
                        self.outlist.append(apstr)
                    #print "outres: " + str(outres)
                    c = c+1
                    #print "reading turn: " + str(c)
                    time.sleep(0.01)

            if self.stopall != True:
                if self.return_func != None:
                    dofunc = self.return_func(self.outlist) 
                else:
                    try:
                        dofunc = self.return_func(['no response'])
                    except:
                        pass
                    return self.outlist            
        else:
            print "Error, aborted!"
            if self.stopall == True:
                fo.close()  
    def stop(self):
        self.stopall = True
        #print "------------------------------------------------"
        #print "------------------------------------------------"        
        #print "All processes stopped!"
        #time.sleep(0.3)
        #print "Status: " + str(self.isAlive())
        #print "------------------------------------------------"
        #print "------------------------------------------------"     

    def run_command(self): 
        returnval = False
        runit = os.popen(self.call, 'w')
        if runit != None:
            runit.flush()
            runit.close()
            returnval = True
        else:
            returnval = False
            
        if self.stopall == True:
            if runit != None:
                try:
                    runit.flush()
                    runit.close()
                except:
                    pass
            #print "*** runit state: " + str(runit)
        return returnval
    
#class PtsWrite_delete_this_class ( Thread ):
#
#    def __init__ (self, pts, command):
#        Thread.__init__(self)
#        self.pts = pts
#        self.command = command
#        self.call = "echo " + self.command + " > " + self.pts
#
#    def run(self):
#        error = False
#        runcom = self.run_command()
#        if runcom != True:
#            error = True        
#            try:
#                fo = open(self.pts,"r")
#            except:
#                #raise IOError, "Couldn't open pts device!"
#                error = True
#            if error != True:
#                commandline = None
#                self.outlist = []
#                c = 0
#                while commandline == None and c < 200:  
#                    commandline = re.search(self.command, fo.readline())
#                    if commandline != None:
#                        if commandline.group() == self.command:
#                            #print "commandline found in output: " + str(commandline.group())
#                            break
#                    else:
#                        print "waiting for command -- " + str(c)                       
#                    c = c+1
#                if commandline == None:
#                    print "Error: command: " + self.command +  " could not launched"               
#        else: 
#            print self.pts + " not found"
#
#    def run_command(self):
#        returnval = False
#        if os.path.exists(self.pts):
#            runit = os.popen(self.call, 'w')
#            print 'runit: ' + str(runit)
#            if runit != None:
#                returnval = True
#                runit.flush()
#                runit.close()
#            else:
#                returnval = False
#            print "PtsWrite done!"
#        return returnval            
            
#class PtsRead_delete_this_class ( Thread ):
#    def __init__ (self, pts, ptsout):
#        Thread.__init__(self)
#        self.pts = pts
#        self.ptsout = ptsout
#        self.outlist = []
#
#    def run(self):
#        #print "PtsRead aufgerufen"
#        if os.path.exists(self.pts):
#            ptsout = self.ptsout
#            lct = 0
#            m = None
#            q = None
#            while os.path.exists(self.pts):
#                outres =  ptsout.readline()
#                outres = string.strip(outres)
#                if lct != 0 and outres != "" and outres != "(qemu)":
#                    self.outlist.append(str(outres))
#                    
#                m = re.search("\w+", outres)
#                q = re.search("(qemu)", outres)
#                lct = lct+1
#                if q != None: 
#                    #print q
#                    lct = 0
#                    ptsout.close()
#                    break
#                time.sleep(0.3)     
#            print "READ DONE!"
#        else: 
#            print self.pts + " not found -  STOP" 
