//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/>.

#include <QtGui>
#include <QTabWidget>
#include <QWebView>
#include "acetoneiso.h"
#include "connections.h"
#include <fcntl.h>
#include <iostream>
#include <QProcess>
#include <QUrl>
#include <QProgressBar>
#include <QDirIterator>
#include <QSystemTrayIcon>
#include"status_mounted_no_boot.h"
#include"md5check.h"
#include"mount.h"
#include"encrypt.h"
#include"foldertoiso.h"
#include"donate.h"
#include"psxrip.h"
#include"compress.h"
#include"converter.h"
#include"isocd.h"
#include"split.h"
#include"play.h"
#include"gencue.h"
#include"database.h"
#include"gmount.h"
#include"eltorito.h"
#include"backup_audio.h"
#include"messages.h"
#include"status_mounted.h"
#include"options.h"
#include"about.h"
#include"progress.h"
#include"manual.h"
#include"udf.h"
#include"vidgen.h"
#include"utube.h"
#include"audiotools.h"
#include"umount_check.h"
#include"iso_from_pcgame.h"
#include"leggirigo.h"
#include"psp.h"
#include"history.h"
#include"erase_cd.h"
#include"erase_dvd.h"
#include"global_functions.h"


acetoneiso::acetoneiso()
{
QPixmap splashpng(":/images/splash.png");
QSplashScreen *splash = new QSplashScreen(splashpng);
splash->show();
splash->showMessage(tr("Loading GUI..."));


  QDir Temp = QDir::temp();
  Temp.mkdir("acetoneiso");
  //Temp.mkdir("acetoneiso_burn");

  QDir Home = QDir::home();
  create_virtual_drives();
  Home.mkdir(".acetoneiso");
  Home.cd(".acetoneiso");



    setupUi(this); // this sets up GUI
    setDockInit();
    status_mounted(); //questa funzione va prima del montaggio da cml altrimenti ho una doppia entry nel montaggio da terminale
    cmlMount();
    
    //connessioni
    connections(); 


listWidget_2->setAcceptDrops(true);
//progress1Bar->setVisible( false );
splash->showMessage(tr("Loading Options..."));
createOption();
initial_get_database();
history_autoclean();
load_history();

//carico tray icon
load_trayicon();

//database label
database_label();

//hide process display and its contents 
hide_process_display();

splash->finish(this);
}


//cattura segnale di chiusura per mandarlo in tray
void acetoneiso::closeEvent(QCloseEvent *event)
{
QDir HomeT = QDir::home();
QFile fileT(HomeT.path() + "/.acetoneiso/acetoneiso_advanced.conf");
fileT.open(QIODevice::ReadOnly | QIODevice::Text);
QString tray = fileT.readAll();

//se false significa che lutente non ha la tray icon abilitato
  if(!tray.contains("enabletrayicon", Qt::CaseInsensitive)) {
    remove_virtual_drives();
    return;
  }

//evita segfault se l'utente abilita la tray icon con close in tray icon abilitato senza ancora aver riavviato per attivare la tray
if (tray_has_loaded == false) {
   remove_virtual_drives();
 return; 
}

//se true significa che lutente ha la tray icon abilitato e in piu vuole che si chiude in tray icon
  if(tray.contains("noclosetrayt", Qt::CaseInsensitive)) {
        if (trayIcon->isVisible()) {
        hide();
        event->ignore();
	}
  }
  else {
   remove_virtual_drives(); //se qui significa che l'utente ha la tray icon abilitato ma che non deve chiudersi in trayicon
  }
fileT.close();
}


//gestisce l'oscuramento nel context menu della tray icon
void acetoneiso::setVisible(bool visible)
{
  
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)) {
   // minimizeAction->setEnabled(visible);
   
   restoreAction->setEnabled(true);
    QMainWindow::setVisible(visible);
  }
  else {
   QMainWindow::setVisible(visible); 
  }
fileT.close();
}
//gestisce cosa fare quando l'utente clicca con il sinistro sulla tray icon
void acetoneiso::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::Trigger:
    case QSystemTrayIcon::DoubleClick:
     
     if (QMainWindow::isMinimized()) {
	QMainWindow::showNormal();   
	return;
      }
     if (QMainWindow::isHidden()) {
        QMainWindow::setVisible(true);  
	QMainWindow::showNormal();   
	return;
      }
      else {
	QMainWindow::hide(); 
	return;
      }

        break;
    case QSystemTrayIcon::MiddleClick:
      
      if (QMainWindow::isMinimized()) {
	QMainWindow::showNormal();   
	return;
      }
     if (QMainWindow::isHidden()) {
        QMainWindow::setVisible(true);  
	QMainWindow::showNormal();   
	return;
      }
      else {
	QMainWindow::hide(); 
	return;
      }
      
        break;
    default:
        ;
    }
}



void acetoneiso::progBarra()
{
      prog.show();
}

void acetoneiso::closeProg()
{
prog.close();
}

void acetoneiso::on_options_nda_activated()
{
QMainWindow::showNormal();
optionsDiag *opt=new optionsDiag;
opt->exec();
}


//gestire che lutente vuole aprire lopzioni direttamente in database
void acetoneiso::call_database_options() {
    QDir Home = QDir::home();
    QFile advanced(Home.path() + "/.acetoneiso/optiondb.conf");
    advanced.remove();
      advanced.open(QIODevice::WriteOnly | QIODevice::Text);
      QTextStream out_adv(&advanced);
      out_adv << ( "must call option directly in database settings\n" );
      advanced.close();
on_options_nda_activated();  
}





void acetoneiso::createOption()
{  
  
    QDir Home = QDir::home();
    QFile advanced(Home.path() + "/.acetoneiso/acetoneiso_advanced.conf");
    if (!advanced.exists()) {
      advanced.open(QIODevice::WriteOnly | QIODevice::Text);
      QTextStream out_adv(&advanced);
      out_adv << ( "TRAYICON = enabletrayicon\n" );
      out_adv << ( "TRAYICON_CLOSE = closetrayicon\n" );
      out_adv << ( "HISTORY_CLEAN = cleanhistory\n" );
      out_adv << ( "HISTORY_REMOVE_FAKE = removefakehistory\n" );
      advanced.close();  
 }


QFile file(Home.path() + "/.acetoneiso/acetoneiso.conf");
if( !file.exists() ) {
   file.open(QIODevice::WriteOnly | QIODevice::Text);
   QTextStream out(&file);
   out << ( "ISO_FROM_FOLDER = standard\n" );
   out << ( "PLAYER = kaffeine\n" );
   out << ( "FILE_BROWSER = kde\n" );
   out << ( "DB = " + Home.path() + "\n" );
   out << ( "recursive = norecursive" "\n" );
   file.close();
 advanced.remove();
QMessageBox::warning(this, "AcetoneISO::First Launch",tr("This is the first time you launch AcetoneISO software.\nIn the next dialog you can set your default file manager, set database and some other things.\nHappy AcetoneISO usage from the team:)"));
on_options_nda_activated();
   }

}


void acetoneiso::on_actionAbout_activated()
{
QMainWindow::showNormal();
aboutDiag *abt=new aboutDiag;
abt->exec();
}

void acetoneiso::on_actionManual_activated()
{
manualDiag *man=new manualDiag;
man->exec();
}


void acetoneiso::setDockPos()
{
QDir Home = QDir::home();
QFile windowStateFile(Home.path() + "/.acetoneiso/gui.state");
    QByteArray state = saveState();

    if(windowStateFile.open(QIODevice::WriteOnly))
    {
      windowStateFile.write(state);
      windowStateFile.close();
    }
}

void acetoneiso::setDockInit()
{
QDir Home = QDir::home();
QFile windowStateFile(Home.path() + "/.acetoneiso/gui.state");
    if(windowStateFile.open(QIODevice::ReadOnly))
    {
      QByteArray bytes = windowStateFile.readAll();
      restoreState(bytes);
      windowStateFile.close();
    }
}


// funzioni burnamento
void acetoneiso::erase_media() {
int c;
c = erase_combobox->currentIndex();
if (c == 0) {
QFile wodim("/usr/bin/wodim");
  if (!wodim.exists()) { 
    QMessageBox::critical(this, "AcetoneISO::Critical", tr("Unable to find wodim in /usr/bin.\nPlease install wodim package.")); 
    return;
  }
erasecd *ecd=new erasecd;
ecd->exec();
}
else {
QFile dvd_tools("/usr/bin/dvd+rw-format");
  if (!dvd_tools.exists()) {
    QMessageBox::critical(this, "AcetoneISO::Critical", tr("Unable to find dvd+rw-format in /usr/bin.\nPlease install dvd+rw-tools package.")); 
    //return;
  }
 //QMessageBox::critical(this, "AcetoneISO::Critical", "da fare");   
erasedvd *edvd=new erasedvd;
edvd->exec();
  }
}









