//This file is part of AcetoneISO. Copyright 2006,2007,2008,2009 Fabrizio Di Marco and Marco Di Antonio  (acetoneiso@gmail.com)
//
//    AcetoneISO 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.
//
//    AcetoneISO 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 AcetoneISO.  If not, see <http://www.gnu.org/licenses/>.

//donazione
void acetoneiso::paypal() {
  QUrl url("http://www.acetoneteam.org/donate.html");
  QDesktopServices::openUrl(url);
}


//funzione che si occupa di vedere se c'e' una virtual drive libera, se c'e' chiama il mount passandogli il percorso dell immagine e del virtual drive libero
void acetoneiso::global_functions_mount(QString immagine_con_percorso) {
QFile fus;
fus.setFileName("/usr/bin/fuseiso");
if (!fus.exists()) {
QMessageBox::critical(this, "AcetoneISO::Warning", "Error: /usr/bin/fuseiso not found.\nPlease install fuseiso package.");
return;
}
  
create_virtual_drives();

QDir Home = QDir::home();
QFile file(Home.path() + "/.acetoneiso/acetoneiso.conf");
file.open(QIODevice::ReadOnly);//lo apro in sola lettura
QString strd = (leggiRigo( 4, &file ));
strd.remove(0,5);
strd.chop(1);
//controllo che se strd finisce con / allora si deve togliere.
if( strd.endsWith( "/" ) ) {
   strd.chop(1);
   }
QString isodamontare =  immagine_con_percorso;

QDir Temp = QDir::temp();
Temp.cd("acetoneiso");
QString percorsoTemp = Temp.path();
QFile Mtab("/etc/mtab");//dichiaro un file Mtab che sarebbe /etc/mtab
Mtab.open(QIODevice::ReadOnly);//lo apro in sola lettura
QString str1 = (Mtab.readAll());//leggo il contenuto del file mtab

QFileInfo fi(isodamontare);
QString onlyfile = fi.fileName();
QString image_with_path = isodamontare;
QFile getfile;
getfile.setFileName(isodamontare);
float bignum = getfile.size();

float divide;
divide = (bignum / 1000) / 1000 ;

QString percorsovirtuale;
int x = 1;
while( x < 8 ) {
   if( !str1.contains( Home.path() + "/virtual-drives/" + QString::number( x ) ) ) {
      percorsovirtuale = ( Home.path() + "/virtual-drives/" + QString::number( x ) );
      Monta( isodamontare, percorsovirtuale );
         while( FUse.waitForFinished() ) { //aspetto che finisca il processo fuse per controllare se è stata montata
         }
         openBrowser( percorsovirtuale, onlyfile, divide, percorsoTemp, image_with_path );
      break;
   }
   else {
      x++;
   }
}
if( x == 8 ) {
      QMessageBox::warning(this, "AcetoneISO::Warning",tr("All Virtual Drives are busy,\n"
							"Unmount some Virtual Drive first!"));
   }
   
   Mtab.close();
   file.close();   
}



//gestisce l'apertura del file manager in base alle opzioni
void acetoneiso::openFileManager(QString immagine_con_percorso) {

QDir Home = QDir::home();//entro nella home utente
QFile file(Home.path() + "/.acetoneiso/acetoneiso.conf");
   file.open(QIODevice::ReadOnly);//lo apro in sola lettura
QString strc = (leggiRigo( 3, &file ));

QString vd = Home.path() + "/virtual-drives/" + immagine_con_percorso;
      
        if(strc.contains("kde", Qt::CaseInsensitive)) { 	// se nelle impostazioni ho come browser kde 
	BRowser.startDetached("kfmclient",QStringList() << "exec" << vd );
	}
	
	if(strc.contains("gnome", Qt::CaseInsensitive)) { 
	BRowser.startDetached("nautilus",QStringList() << vd );
	}
	
	if(strc.contains("thunar", Qt::CaseInsensitive)) { 
	BRowser.startDetached("thunar",QStringList() << vd );
	}
	
	if(strc.contains("nofilemanager", Qt::CaseInsensitive)) { 
      QMessageBox::warning(this, "AcetoneISO::Warning",tr("Even though the image is mounted, in the options you specified to not open a file manager.\nIf you want to change this behaviour, please open Options and set file manager there."));
	}
	
	
file.close();  
  
}


//funzione che smonta limmagine dal display del montaggio
void acetoneiso::umount() {
if (!listWidget_2->currentItem() == 0)

{
QString oggetto(listWidget_2->currentItem()->text());
QChar periferica(oggetto[4]);
QString f1_string(periferica);//
QDir percorso = ( (QDir::home()).path() + "/virtual-drives/" + periferica );
QDir Temp = QDir::temp();

QFile f1;
f1.setFileName( Temp.path() + "/acetoneiso/" + f1_string );


QMessageBox msgBox;
msgBox.setText(tr("You decided to unmount:\n") + oggetto + tr("\nAre you sure?"));
 msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
 switch (msgBox.exec()) {
 case QMessageBox::Yes:
    {
      //continue below
     }
     break;
 case QMessageBox::No:
 {
  return; //exit
 }
     break;
 default:
     // should never be reached
     break;
 }


FUsermount.start("fusermount",QStringList() << "-u" << "-z" << percorso.path() );

int riga = listWidget_2->currentRow() ;
listWidget_2->takeItem( riga  );
f1.remove();
FUsermount.waitForFinished();
remove_virtual_drives();
}
else {
QMessageBox::warning(this, "AcetoneISO::Warning",tr( "select an image to unmount from the virtual-drives display" ));
}

}


//creo virtual drives
void acetoneiso::create_virtual_drives() {
  QDir Home = QDir::home();
  Home.mkdir("virtual-drives");
  Home.cd("virtual-drives");
  Home.mkdir("1");
  Home.mkdir("2");
  Home.mkdir("3");
  Home.mkdir("4");
  Home.mkdir("5");
  Home.mkdir("6");
  Home.mkdir("7");
  Home.mkdir("dvd");
}

//cancello cartella virtual-drives
void acetoneiso::remove_virtual_drives() {
  QDir Home = QDir::home();
   Home.rmdir("virtual-drives/1");
   Home.rmdir("virtual-drives/2");
   Home.rmdir("virtual-drives/3");
   Home.rmdir("virtual-drives/4");
   Home.rmdir("virtual-drives/5");
   Home.rmdir("virtual-drives/6");
   Home.rmdir("virtual-drives/7");
   Home.rmdir("virtual-drives/dvd");
   Home.rmdir("virtual-drives");
}


//carico tray icon
void acetoneiso::load_trayicon() {
    AboutAction = new QAction(tr("About AcetoneISO"), this);
    connect(AboutAction, SIGNAL(triggered()), this, SLOT(on_actionAbout_activated() ));
    OptionsAction = new QAction(tr("Options"), this);
    connect(OptionsAction, SIGNAL(triggered()), this, SLOT(on_options_nda_activated() ));
    
    MountAction = new QAction(tr("Mount Image"), this);
    connect(MountAction, SIGNAL(triggered()), this, SLOT(mount()));
    restoreAction = new QAction(tr("&Restore"), this);
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
    quitAction = new QAction(tr("&Quit"), this);
    connect(quitAction, SIGNAL(triggered()), this, SLOT(quitto()));
    
    QIcon about_icon( ":/images/Acetino2.png" );
    QIcon options_icon( ":/images/aoptions.png" );
    QIcon mount_icon( ":/images/cdwriter_mount.png" );
    QIcon restore_icon( ":/images/file_manager.png" );
    QIcon exit_icon( ":/images/application-exit.png" ); 
    quitAction->setIcon(exit_icon);
    restoreAction->setIcon(restore_icon);
    MountAction->setIcon(mount_icon);
    AboutAction->setIcon(about_icon);
    OptionsAction->setIcon(options_icon);

tray_has_loaded = false;   
//load tray icon
QDir HomeT = QDir::home();
QFile fileT(HomeT.path() + "/.acetoneiso/acetoneiso_advanced.conf");
fileT.open(QIODevice::ReadOnly | QIODevice::Text);
QString tray = fileT.readAll();
  if(tray.contains("enabletrayicon", Qt::CaseInsensitive)) {
    trayIcon = new QSystemTrayIcon();
    QIcon icon = QIcon(":/images/Acetino2.png");
    trayIcon->setIcon(icon);
    trayIcon->show();
    trayIcon->setToolTip(tr("AcetoneISO I love You!"));
    
    trayIconMenu = new QMenu(this);
    
    trayIconMenu->addAction(AboutAction);
    trayIconMenu->addAction(OptionsAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(MountAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(restoreAction);
    trayIconMenu->addAction(quitAction);
    trayIcon->setContextMenu(trayIconMenu);    
    tray_has_loaded = true;
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
  }  
}

//gestisco cosa fare quando lutente clicca su esci della tray icon
void acetoneiso::quitto() {
 remove_virtual_drives();
 QCoreApplication::quit(); 
}


//gestisco quando cambia la selezione nel display del montaggio, cosi avverto il bottone smonta che cambia nome con il nome
//dell'immagine
void acetoneiso::mountdisplayClicked() {
  
  int size = listWidget_2->selectedItems().size();  
  if (size < 1) {
    pushButton_2->setText(tr("Unmount"));
    actionUnmount_Image->setText(tr("Unmount Image"));
    pushButton_2->setEnabled(false);
    actionUnmount_Image->setEnabled(false);
   return; 
  }

pushButton_2->setEnabled(true); 
actionUnmount_Image->setEnabled(true);
QString testo(listWidget_2->selectedItems()[0]->text()) ;
QStringList smonta = testo.split(QRegExp("\\s+"));
//gestisce lo spazio nel nome altrimenti lo taglia
       int strl = smonta.size();
       smonta.removeAt(strl - 1);
       smonta.removeAt(0);
       smonta.removeAt(0);
       strl = smonta.size();
       QString h = "";
       int ss = 0;
       while (ss < strl) {
	 h = h.append(smonta[ss]);
	 ss = ss + 1;
       }
h = tr("Unmount") + " " + h;
pushButton_2->setText(h);
actionUnmount_Image->setText(h);
  
}



//nasconde display del processo
void acetoneiso::hide_process_display() {
textBrowser->clear();
textBrowser->hide();
pushButton_6->setEnabled(false);
pushButton_6->hide();
label_6->hide();
verticalSpacer->changeSize( 0,0,QSizePolicy::Ignored ); 
}

//mostra il display del processo in esecuzione e i relativi bottoni, label ecc
void acetoneiso::showProgressDisplay() {
  label_6->show();
  pushButton_6->show();
  pushButton_6->setEnabled(false);
  verticalSpacer->changeSize( 20,18,QSizePolicy::Fixed );
  textBrowser->clear();
  textBrowser->show();
  disable_all_button_processes();
}

//disable all buttons per evitare di fare doppi processi in contemporanea
void acetoneiso::disable_all_button_processes() {
  menuConversion->setEnabled(false);
  menuUtilities->setEnabled(false);
  menuArchive_Manager->setEnabled(false);
  menuXvid_Videos->setEnabled(false);
  menuAudio->setEnabled(false);
}

//riabilita tutti i bottoni disabilitati (che evitavano piu di un processo in contemporanea
void acetoneiso::restore_all_button_processes() {
  menuConversion->setEnabled(true);
  menuUtilities->setEnabled(true);
  menuArchive_Manager->setEnabled(true);
  menuXvid_Videos->setEnabled(true);
  menuAudio->setEnabled(true);
}


//fa il display del processo vidgen
void acetoneiso::updateProgressDisplay_vidgen() {
process_output = VIdgen->readAllStandardOutput(); 
textBrowser->setPlainText(process_output);
}
//fa il display del processo flv
void acetoneiso::updateProgressDisplay_flv() {
process_output = FLv->readAllStandardOutput(); 
textBrowser->setPlainText(process_output);
}
//fa il display del processo extractaudiofromvideo
void acetoneiso::updateProgressDisplay_extractaudiofromvideo() {
process_output = extractaudiofromvideo->readAllStandardOutput(); 
textBrowser->setPlainText(process_output);
}
//fa il display del processo utube
void acetoneiso::updateProgressDisplay_UTube() {
process_output = UTube->readAllStandardOutput(); 
textBrowser->setPlainText(process_output);
}
//fa il display di mkisofs
void acetoneiso::updateProgressDisplay_MKisofs() {
process_output = MKisofs->readAllStandardOutput(); 
textBrowser->setPlainText(process_output); 
}
//fa il display di convert to iso e extract (poweriso)
void acetoneiso::updateProgressDisplay_POweriso() {
process_output = POweriso->readAllStandardOutput(); 
textBrowser->setPlainText(process_output);  
}
//fa il display del convertitore mac dmg ad iso(macimg)
void acetoneiso::updateProgressDisplay_MAcimg() {
process_output = MAcimg->readAllStandardOutput(); 
textBrowser->setPlainText(process_output);   
}
//fa il display del backup cd audio
void acetoneiso::updateProgressDisplay_BAckaudio() {
process_output = BAckaudio->readAllStandardOutput(); 
textBrowser->setPlainText(process_output);   
}
//fa il display del rip cd psx
void acetoneiso::updateProgressDisplay_PSxrip() {
process_output = PSxrip->readAllStandardOutput(); 
textBrowser->setPlainText(process_output);     
}
//display del rip dvd a xvid pass 1
void acetoneiso::updateProgressDisplay_RIp() {
process_output = RIp->readAllStandardOutput(); 
textBrowser->setPlainText(process_output);  
}
//display del rip dvd a xvid pass 2
void acetoneiso::updateProgressDisplay_RIp2() {
process_output = RIp2->readAllStandardOutput(); 
textBrowser->setPlainText(process_output);  
}
//fa display del rar password
void acetoneiso::updateProgressDisplay_RAR() {
process_output = RAR->readAllStandardOutput(); 
textBrowser->setPlainText(process_output);  
}








