#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os,sys,subprocess,platform
from PyQt4 import QtGui
from gui.ui_multibootusb import Ui_Dialog
import gen_fun


class AppGui(QtGui.QDialog,Ui_Dialog):

    def on_Qemu_Browse_iso_Click(self):

        self.ui.lineEdit_2.clear()

        qemu = self.check_qemu_exist()

        if not qemu is None:
        
            qemu_iso_link = QtGui.QFileDialog.getOpenFileName(self, 'Select an iso...', "",  "ISO Files (*.iso)")
        else:
            print "QEMU does not exist.\nPlease install qemu package to avail this feature."
            QtGui.QMessageBox.information(self, 'No QEMU...', 'Please install qemu package to avail this feature.')
            qemu_iso_link = None

        if not qemu_iso_link is None:
            self.ui.lineEdit_2.insert (qemu_iso_link)
        else:
            print ("File not selected.")
            
    def on_Qemu_Boot_iso_Click(self):

        if not self.ui.lineEdit_2.text():
            QtGui.QMessageBox.information(self, 'No ISO...', 'No ISO selected.\n\nPlease choose an iso and click Boot ISO.')
        else:
            qemu = self.check_qemu_exist()
            qemu_iso_link = str(self.ui.lineEdit_2.text())
            if qemu is None:
                print "QEMU does not exist.\nPlease install qemu package to avail this feature."
                QtGui.QMessageBox.information(self, 'No QEMU...', 'Please install qemu to avail this feature.')
            else:
                ram = self.qemu_iso_ram()
                if not ram is None:
                    self.ui.lineEdit_2.clear()
                    if platform.system() == "Windows":
                        try:
                            print "Executing ==>  " + qemu + " -cdrom " + str(qemu_iso_link) + " -boot d -m " + ram
                            subprocess.Popen(qemu + " -cdrom " + str(qemu_iso_link) + " -boot d -m " + ram, shell=True)
                        except:
                            QtGui.QMessageBox.information(self, 'Error...', 'Unable to start QEMU.')
                    else:
                        print qemu + ' -m ' + ram + ' -cdrom ' + str(qemu_iso_link) + ' -boot d'
                        try:
                            print "Executing ==>  " + qemu + " -cdrom " + str(qemu_iso_link) + " -boot d -m " + ram
                            subprocess.Popen(qemu + " -cdrom " + str(qemu_iso_link) + " -boot d -m " + ram, shell=True)
                        except:
                            QtGui.QMessageBox.information(self, 'Error...', 'Error booting ISO\n'
                                                                            'Unable to start QEMU.')
                        '''
                        if os.geteuid() == 0:
                            var.qemu_iso = subprocess.Popen(var.qemu + ' -m ' + ram + ' -cdrom ' + str(qemu_iso_link) + ' -boot d', shell=True).pid
                        else:
                            var.qemu_iso = subprocess.Popen('echo ' + var.password + ' | sudo -S ' + var.qemu + ' -m ' + ram + ' -cdrom ' + str(qemu_iso_link) + ' -boot d', shell=True).pid
                        '''
                else:
                    QtGui.QMessageBox.information(self, 'No ram...', 'No ram selected.\n\nPlease choose any ram value and click Boot ISO.')


    def on_Qemu_Boot_usb_Click(self, user_password, usb_disk):

        qemu = self.check_qemu_exist()

        if qemu is None:
            print "QEMU does not exist.\nPlease install qemu package to avail this feature."
            QtGui.QMessageBox.information(self, 'No QEMU...', 'Please install qemu to avail this feature.')
        else:
            ram = self.qemu_usb_ram()
            if ram is None:
                QtGui.QMessageBox.information(self, 'No ram...', 'No ram selected.\n\nPlease choose any ram value and click Boot USB.')
            else:
                if platform.system() == "Windows":
                    disk_number = self.get_physical_disk_number(usb_disk)
                    parent_dir = os.getcwd()
                    os.chdir(gen_fun.resource_path(os.path.join("tools", "qemu")))
                    try:
                        print "Executing ==>  " + qemu + " -L . -boot c -m " + ram + " -hda //./PhysicalDrive" + disk_number
                        subprocess.Popen("qemu-system-x86_64.exe -L . -boot c -m "  + ram + " -hda //./PhysicalDrive" + disk_number, shell=True)
                    except:
                        QtGui.QMessageBox.information(self, 'Error...', 'Error booting USB\n'
                                                                            'Unable to start QEMU.')
                    os.chdir(parent_dir)
                elif platform.system() == "Linux":
                    try:
                        if os.geteuid() == 0:
                            print "Executing ==>  " + qemu + ' -hda ' + usb_disk[:-1] + ' -m ' + ram + ' -vga std'
                            subprocess.Popen(qemu + ' -hda ' + usb_disk[:-1] + ' -m ' + ram + ' -vga std', shell=True)
                        else:
                            print "Executing ==>  " + qemu + ' -hda ' + usb_disk[:-1] + ' -m ' + ram + ' -vga std'
                            subprocess.Popen('echo ' + user_password + ' | sudo -S ' + qemu + ' -hda ' + usb_disk[:-1]
                                                                        + ' -m ' + ram + ' -vga std', shell=True)
                    except:
                        QtGui.QMessageBox.information(self, 'Error...', 'Error booting USB\n\nUnable to start QEMU.')

    def qemu_iso_ram(self):

        if self.ui.ram_iso_256.isChecked():
            return str(256)
        elif self.ui.ram_iso_512.isChecked():
            return str(512)
        elif self.ui.ram_iso_768.isChecked():
            return str(768)
        elif self.ui.ram_iso_1024.isChecked():
            return str(1024)
        elif self.ui.ram_iso_2048.isChecked():
            return str(2048)
        else:
            return None

    def qemu_usb_ram(self):
        if self.ui.ram_usb_256.isChecked():
            return str(256)
        if self.ui.ram_usb_512.isChecked():
            return str(512)
        if self.ui.ram_usb_768.isChecked():
            return str(768)
        if self.ui.ram_usb_1024.isChecked():
            return str(1024)
        if self.ui.ram_usb_2048.isChecked():
            return str(2048)
        else:
            return None
            
    def check_qemu_exist(self):
        if platform.system() == "Linux":
            if subprocess.call('which qemu-system-x86_64', shell=True) == 0:
                print "qemu-system-x86_64 exists..."
                qemu = "qemu-system-x86_64"
            elif subprocess.call('which qemu', shell=True) == 0:
                print "qemu exists"
                qemu = "qemu"
            else:
                qemu = None

            if qemu:
                return qemu
            else:
                return None
        elif platform.system() == "Windows":
            print gen_fun.resource_path(os.path.join("tools", "qemu", "qemu-system-x86_64.exe"))
            return gen_fun.resource_path(os.path.join("tools", "qemu", "qemu-system-x86_64.exe"))

    def get_physical_disk_number(self, usb_disk):
        import wmi
        c = wmi.WMI ()
        for physical_disk in c.Win32_DiskDrive ():
            for partition in physical_disk.associators ("Win32_DiskDriveToDiskPartition"):
                for logical_disk in partition.associators ("Win32_LogicalDiskToPartition"):
                    if logical_disk.Caption == usb_disk:
                        """
                        print physical_disk.Caption
                        print partition.Caption
                        print logical_disk.Caption
                        """
                        print "Physical Device Number is " + partition.Caption[6:-14]
                        return str(partition.Caption[6:-14])