#!/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 gobject
import qemulator
import qml_tools

try:
    import pygtk
    pygtk.require("2.0")
    
except:
      print "pygtk 2.0 is not installed"
try:
    import gtk
    import gtk.glade
    
except:
    print "gtk and/or glade is not installed - exiting..."
    sys.exit(1)
    
try:
    import gettext
    import locale
except:
    print "locale and/or gettext for language support not installed"
    sys.exit(1)        
    
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', '' )

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)
tooltips = gtk.Tooltips() 

homedir = os.path.expanduser('~/.qemulator')
configdir = homedir + "/config"
libdir = basedir + "/lib/qemulator"    
    
class CreateImage:
    def __init__(self, imagespath, callback_func=None):
        self.imagespath = imagespath
        self.callback_func = callback_func
        self.newimagename = ""
        self.newimagetarget = None
        self.newimagebase = None
        self.newimagecompressed = False
        self.newimageencrypt = False
        self.newimageformat = 'Auto'
        self.newimage_size = 1024
        
        self.init_create_image()
#        while self.newimage == None:
#            return
        #return self.newimage
    
    
    def init_create_image(self):
        self.gladefile = libdir + "/qemulator.glade"
        self.Wtree_create_image = gtk.glade.XML(self.gladefile, "dialog_create_image", APP)
        self.dialog_create_image = self.Wtree_create_image.get_widget("dialog_create_image")
        
        self.dialog_create_image.set_keep_above(True)
        ## widgets of the new image dialog
        
        self.filechooserbutton_newimage_dest = self.Wtree_create_image.get_widget("filechooserbutton_newimage_dest")
        self.filechooserbutton_newimage_base = self.Wtree_create_image.get_widget("filechooserbutton_newimage_base")
        self.buttonEjectBaseimage = self.Wtree_create_image.get_widget("buttonEjectBaseimage")
        self.entry_newimage_name = self.Wtree_create_image.get_widget("entry_newimage_name")
        self.combobox_newimage_format = self.Wtree_create_image.get_widget("combobox_newimage_format")
        self.spinbutton_newimage_size = self.Wtree_create_image.get_widget("spinbutton_newimage_size")
        self.combobox_newimage_sizeunit = self.Wtree_create_image.get_widget("combobox_newimage_sizeunit")
        self.checkbuttonNewimageCompressed = self.Wtree_create_image.get_widget("checkbuttonNewimageCompressed")
        self.checkbuttonNewimageEncrypted = self.Wtree_create_image.get_widget("checkbuttonNewimageEncrypted")
        self.button_create_image = self.Wtree_create_image.get_widget("button_create_image")        
        
        
        self.combobox_newimage_sizeunit.set_active(0)
        self.set_newimagesize()
        self.combobox_newimage_format.set_active(0)
        self.set_newimageformat()    
          
        self.filechooserbutton_newimage_dest.set_filename(self.imagespath)
        self.set_newimage_folder()
        
        try:
            #print 'changed to: ' + str(self.settings["imagespath"])
            filechooserbutton_newimage_base.set_current_folder(self.imagespath)
        except:
            pass        
        dic = {"on_dialog_create_image_response" : self.dialog_create_image_response
        # handlers for the new image dialog
        , "on_filechooserbutton_newimage_dest_selection_changed" : self.set_newimage_folder
        , "on_filechooserbutton_newimage_base_selection_changed" : self.on_filechooserbutton_newimage_base_selection_changed
        , "on_buttonEjectBaseimage_clicked" : self.on_buttonEjectBaseimage_clicked
        , "on_entry_newimage_name_changed" : self.on_entry_newimage_name_changed
        , "on_combobox_newimage_format_changed" : self.set_newimageformat
        , "on_spinbutton_newimage_size_changed" : self.set_newimagesize
        , "on_combobox_newimage_sizeunit_changed" : self.set_newimagesize
        , "on_checkbuttonNewimageCompressed_toggled" : self.on_checkbuttonNewimageCompressed_toggled
        , "on_checkbuttonNewimageEncrypted_toggled" : self.on_checkbuttonNewimageEncrypted_toggled
        , "on_button_create_image_clicked" : self.create_newimage
        }
        self.Wtree_create_image.signal_autoconnect(dic)  
        
    def set_newimage_folder(self, *widget):
        self.newimagepath = self.filechooserbutton_newimage_dest.get_filename()
        #print "path: " + self.newimagepath
        
    def on_filechooserbutton_newimage_base_selection_changed(self, *widget):
        self.newimagebase = self.filechooserbutton_newimage_base.get_filename()
        #print "path: " + self.newimagepath  
    def on_buttonEjectBaseimage_clicked(self, widget):
        try:
            #print 'changed to: ' + str(self.settings["imagespath"])
            filechooserbutton_newimage_base.set_current_folder(self.imagespath)
        except:
            #print 'cleared'
            self.filechooserbutton_newimage_base.unselect_all()
            
    def on_entry_newimage_name_changed(self, *widget):
        self.newimagename = self.entry_newimage_name.get_text() 
        #print "name: " + self.newimagename   
        
    def on_checkbuttonNewimageCompressed_toggled(self, widget):
        self.newimagecompressed = widget.get_active()
        
    def on_checkbuttonNewimageEncrypted_toggled(self, widget):
        self.newimageencrypt = widget.get_active()        
        
    def set_newimageformat(self, *widget):
        #self.newimageformat = self.combobox_newimage_format.get_active()
        active = self.combobox_newimage_format.get_active()
        model = self.combobox_newimage_format.get_model()
        row = model[active]
        self.newimageformat = row[0]
        if self.newimageformat == 'qcow' or self.newimageformat == 'qcow2':
            self.checkbuttonNewimageCompressed.set_sensitive(True)
            self.checkbuttonNewimageEncrypted.set_sensitive(True)
        else:
            self.checkbuttonNewimageCompressed.set_sensitive(False)
            self.checkbuttonNewimageCompressed.set_active(False)
            self.checkbuttonNewimageEncrypted.set_sensitive(False)
            self.checkbuttonNewimageEncrypted.set_active(False)     
            
        
    def set_newimagesize(self, *widget):
        sizevalue = self.spinbutton_newimage_size.get_value()
        #sizeunit = self.combobox_newimage_sizeunit.get_active()
        active = self.combobox_newimage_sizeunit.get_active()
        model = self.combobox_newimage_sizeunit.get_model()
        row = model[active]
        sizeunit = row[0]
        
        if sizeunit == "KB":
            self.newimage_size = str(int(sizevalue))
        elif sizeunit == "MB":
            self.newimage_size = str(int(sizevalue)) + "M"
        elif sizeunit == "GB":
            self.newimage_size = str(int(sizevalue)) + "G" 
        else:
            self.newimage_size = str(int(sizevalue))
        #print "size: " + self.newimage_size
        
    def create_newimage(self, widget):
        qemuparams = {}
        if self.newimagename != "":
            self.newimagetarget = self.newimagepath + "/" + self.newimagename
            if self.newimageformat != "Auto":
                qemuparams['formatcommand'] = " -f " + self.newimageformat
            else:
                qemuparams['formatcommand'] = ''                
            #else:
            #    qemuparams['formatcommand'] = ""
                
            #qemuparams['newimage_size'] = ' ' + self.newimage_size
            if self.newimagecompressed == True:
                qemuparams['compressed'] = " -c"
            else:
                qemuparams['compressed'] = ''
                
            if self.newimageencrypt == True:
                qemuparams['encrypted'] = " -e" 
            else:
                qemuparams['encrypted'] = ''                
            
            if self.newimagebase == True:
                qemuparams['baseimage'] = " -b " + str(self.newimagebase)
            else:
                qemuparams['baseimage'] = ''                
                            
            options = ''
            for key in qemuparams.keys():
                option = qemuparams[key]
                options = options + option  
                              
            #command = "qemu-img create " + formatcommand + " " + self.newimagetarget + " " + self.newimage_size
            command = "qemu-img create " + qemuparams['compressed'] + qemuparams['encrypted'] + qemuparams['baseimage'] + qemuparams['formatcommand'] + " " + self.newimagetarget + " " + self.newimage_size
            #print command
            print 'command: ' + str(command)
            runcreate = os.popen(command).read()
            message = command + "\n" + str(runcreate)
            #print str(message)
            #self.init_messages_dialog(str(message))
            infodialog = qml_tools.Dialog("longtext", message, 'Result:') 
            #self.messagesbuffer.set_text(str(message))
            #self.refresh_ilist()
            self.newimage = self.newimagetarget
            return self.newimagetarget
        else:
            message = _('No name given for the new image!\nplease enter a name and try again.')
            #self.init_messages_dialog(message)
            infodialog = qml_tools.Dialog("longtext", message, 'Error:') 
            return None
            
    def dialog_create_image_response(self, widget, response, *entry):    
        if response == gtk.RESPONSE_CLOSE:
            if self.callback_func != None:
                self.callback_func(self.newimagetarget)
            widget.destroy ()
            pass 
        
    def return_newimage(self):
        return self.newimage