#!/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.
from os import path
import os
import sys
import pickle
import time
import threading
from threading import Thread
import locale
import gettext
import gtk
import gtk.glade

import qemulator

import Run_Defaultapp

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

current_path = os.path.realpath(__file__)
basedir = os.path.dirname(os.path.realpath(__file__))
if not os.path.exists(os.path.join(basedir, "main.py")):
    if os.path.exists(os.path.join(os.getcwd(), "main.py")):
        basedir = os.getcwd()
sys.path.insert(0, basedir)   

basedir = basedir.replace ( '/bin', '' ) 
basedir = basedir.replace ( '/lib/qemulator', '' ) 
sys.path.append(basedir)   
bindir = basedir + "/bin"
libdir = basedir + "/lib/qemulator"
sharedir = basedir + "/share/qemulator"
pixmapdir = basedir + "/share/pixmaps/qemulator"
homedir = os.path.expanduser('~/.qemulator')
configdir = homedir + "/config"

APP = 'Qemulator'
#DIR = 'locale'
DIR = basedir + '/share/locale'
#print "DIR: " + DIR
locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain(APP, DIR)
gettext.textdomain(APP)
_ = gettext.gettext

gtk.glade.bindtextdomain(APP, DIR)
gtk.glade.textdomain(APP)

class Statefiles:
    def __init__(self, bootimage, settings):
        self.statefiles_dir = homedir + "/statefiles"
        self.bootimage = bootimage
        self.translated_name = self.bootimage.replace ( '/', '_' )
        self.settings = settings
        
    def load_statefiles(self):
        self.storedstates = []
        if os.path.exists(self.statefiles_dir):
            thisjobdir = self.statefiles_dir + "/" + self.translated_name
            if os.path.exists(thisjobdir):
                for file in os.listdir(thisjobdir):
                    #print "file: " + str(file)
                    self.storedstates.append(str(file))
        self.storedstates.sort()
        return self.storedstates 
    
    def delete_statefile(self, filename):
        thisjobdir = self.statefiles_dir + "/" + self.translated_name
        abs_path = path.abspath(thisjobdir + "/" + filename)
        if os.path.isfile(abs_path):
            os.remove(abs_path)
            time.sleep(0.3)        
        
        print "state deleted: " + str(abs_path) 
        
    def statefiles_displaynames(self, data): 
        outdata = []
        for item in data:
            oitem = str(item.replace ( '_', ' ' ))
            outdata.append(oitem)
        return outdata            

class Screenshots:
    def __init__(self, bootimage, settings):
        self.screenshot_dir = homedir + "/screenshots"
        self.bootimage = bootimage
        self.translated_name = self.bootimage.replace ( '/', '_' )
        self.settings = settings
        
    def load_screenshots(self):
        self.storedshots = []
        if os.path.exists(self.screenshot_dir):
            thisjobdir = self.screenshot_dir + "/" + self.translated_name
            if os.path.exists(thisjobdir):
                for file in os.listdir(thisjobdir):
                    #print "file: " + str(file)
                    self.storedshots.append(str(file))
        self.storedshots.sort()
        return self.storedshots
    
    def delete_screenshot(self, filename):
        thisjobdir = self.screenshot_dir + "/" + self.translated_name
        abs_path = path.abspath(thisjobdir + "/" + filename)
        if os.path.isfile(abs_path):
            os.remove(abs_path)
            time.sleep(0.3)        
        #print "screenshot deleted: " + str(abs_path)
        
    def screenshots_displaynames(self, data): 
        outdata = []   
        #data = self.storedstates
        for item in data:
            oitem = str(item.replace ( '.ppm', '' ))
            oitem = str(oitem.replace ( '_', ' ' ))
            outdata.append(oitem)
        return outdata   
    
    def run_imageviewer(self, imagefile):       
        if imagefile != "":
            screenshot_path = self.screenshot_dir + "/" + self.translated_name + "/" + imagefile
            
            viewer = self.settings["helperapps_imageviewer"]
            if viewer != '':
                command = viewer + " " + screenshot_path
                returnval = False
                runit = RunExternalApp(command)
                runit.start()
                #return returnval 
            else:                
                runit = Run_Defaultapp
                rundefault = runit.open(screenshot_path)
                if rundefault != True:
                    dialogtitle = _('Error!')
                    dialogtext = _('Default application for this filetype could not be detected!\n\
Please select a custom application in main settings.')
                    dialog_markup = "<b>" + dialogtext + "</b>"
                    errordialog = qemulator.Dialog("error", dialog_markup, dialogtitle)                    
                
             
    
class Wavecaptures:
    def __init__(self, bootimage, settings):
        self.capture_dir = homedir + "/capture"
        self.bootimage = bootimage
        self.translated_name = self.bootimage.replace ( '/', '_' )
        self.settings = settings
        
    def load_captures(self):
        self.storedcapts = []
        if os.path.exists(self.capture_dir):
            thisjobdir = self.capture_dir + "/" + self.translated_name
            if os.path.exists(thisjobdir):
                for file in os.listdir(thisjobdir):
                    #print "file: " + str(file)
                    self.storedcapts.append(str(file))
        self.storedcapts.sort()
        return self.storedcapts    
    
    def delete_capture(self, filename):
        thisjobdir = self.capture_dir + "/" + self.translated_name
        abs_path = path.abspath(thisjobdir + "/" + filename)
        if os.path.isfile(abs_path):
            os.remove(abs_path)
            time.sleep(0.3)        
        
        print "capture deleted: " + str(abs_path)    
        
    def captures_displaynames(self, data): 
        outdata = []
        for item in data:
            oitem = str(item.replace ( '.wav', '' ))
            oitem = str(oitem.replace ( '_', ' ' ))
            
            outdata.append(oitem)
        return outdata  
    
    def run_audioplayer(self, audiofile):    
        if audiofile != "":
            capture_path = self.capture_dir + "/" + self.translated_name + "/" + audiofile
            viewer = self.settings["helperapps_audioplayer"]
            if viewer != '':
                command = viewer + " " + capture_path
                returnval = False
                runit = RunExternalApp(command)
                runit.start()
                #return returnval 
            else:                
                runit = Run_Defaultapp
                rundefault = runit.open(capture_path)
                if rundefault != True:
                    dialogtitle = _('Error!')
                    dialogtext = _('Default application for this filetype could not be detected!\n\
Please select a custom application in main settings.')
                    dialog_markup = "<b>" + dialogtext + "</b>"
                    errordialog = qemulator.Dialog("error", dialog_markup, dialogtitle)                    
                
                                                         
        
class RunExternalApp ( Thread ):
    def __init__ (self, command):
        Thread.__init__(self)
        self.command = command     
        print "Run App called with command: " + str(self.command)
    def run(self):
        runit = os.popen(self.command, 'r')
        print str(runit)
        return str(runit)
        print "command done!"  
        
def run_command(command):
        if command != '':
            child_stdin, child_stdout, child_stderr = os.popen3(command)
            child_stdin.close()    
            errormesg = child_stderr.readlines()
            resultmesg = child_stdout.readlines()
            if errormesg != []:
                #self.general_error = True
                print "Error: " + str(errormesg)
                returnmesg = errormesg
                child_stderr.close()
                child_stdout.close()
            else:
                returnmesg = resultmesg
        else:
            returnmesg = "no command given!"
        return returnmesg                  
                 
             