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

void acetoneiso::clear_history() {  
  
  int a;
  a = comboBox->currentIndex();
  QDir Home = QDir::home();
  QFile history_conf(Home.path() + "/.acetoneiso/history.conf");

  if (a == 0) { 
    
 int items = history->count();   
// qDebug() << items;
 if (items < 1) {
   history_conf.close();
QMessageBox::information(this, "AcetoneISO",tr("The History display is already empty!")); 
return;
 }
 
QMessageBox msgBox;
msgBox.setText(tr("You are about to clear the History display.\nThis won't delete the images from hard disk.\nClear History?"));
 msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
 switch (msgBox.exec()) {
 case QMessageBox::Yes:
    {
      //continue below
     }
     break;
 case QMessageBox::No:
 {
   history_conf.close();
  return; //exit
 }
     break;
 default:
     // should never be reached
     break;
 }
 
    history->clear();
    history_conf.remove();
  }
 
  if (a == 1) {    
    int boot = 1;
    remove_non_images_history(boot);
  }
 
}


void acetoneiso::remove_non_images_history(int boot) {
//QMessageBox::warning(this, "AcetoneISO::First Launch","lol");
	
	bool image_exists = false;
	QDir Home = QDir::home();
	QFile history_conf(Home.path() + "/.acetoneiso/history.conf");
	history_conf.open(QIODevice::ReadWrite);
	QTextStream history_out(&history_conf);

	
	QString history_line = history_out.readAll();  
	QStringList list = history_line.split("\n",QString::SkipEmptyParts);
	int size = list.size();
	int read_i = 0;

	
	while (read_i < size) {
	 // qDebug() << list[read_i];
	 QFile image(list[read_i]);
	  
	  if (!image.exists()) {
	    //qDebug() << "Io non esisto " << list[read_i];
	    image_exists = true;
	    list.removeAt(read_i);
	    size = size - 1;
	  }
	  read_i++;
	}
	
	history_conf.close();
	history_conf.remove();
	
	QFile history_new(Home.path() + "/.acetoneiso/history.conf");
	history_new.open(QIODevice::ReadWrite);
	QTextStream history_out_new(&history_new);
	
	int i_new = 0;
	int size_new = list.size();
	while (i_new < size_new) {
	 
	  //qDebug() << list[i_new];
	  
	  history_out_new << ( list[i_new] + "\n");
	  
	  i_new++;
	}
	history_new.close();
	history->clear();
	
	load_history();

	if (image_exists) {
	  if (boot != 2) {
	   //sara' uguale a 2 quando un utente decide di eliminare un file dal context menu
	   //in caso di 2, non voglio che mi da questo messaggio
	    QMessageBox::information(this, "AcetoneISO",tr("All images that don't exist have been removed from History")); 
	  }
	}
	else {
	  //sara' uguale a 1 solo quando manualmente lutente decide di fare quest'azione. all'avvio boot = 0
	  if (boot == 1) {
	    int items = history->count();   
	      // qDebug() << items;
	    if (items < 1) {
	      history_conf.close();
	      QMessageBox::information(this, "AcetoneISO",tr("The History display is already empty!")); 
	      return;
	    }
	    else {
	      QMessageBox::information(this, "AcetoneISO",tr("All images in History fisically exist!"));  
	 
	     }
	  }
	  
	}
	
	image_exists = false;
	
}

//gestisce doppio click in cronologia
void acetoneiso::historydoubleclickmount(QListWidgetItem *itemh) {
 immagine_con_percorso = ( (itemh->text()));//da ora ho in isodamontare il file con tutto il suo percorso.
 
//controllo che esiste il file
QFile image_exists(immagine_con_percorso);
if (!image_exists.exists()) {
  QMessageBox::critical(this, "AcetoneISO",tr("The image ") + immagine_con_percorso  + tr(" doesn't exist.\nI'll remove it from history display."));
    int boot = 2;
    remove_non_images_history(boot);
  return;
  }
global_functions_mount(immagine_con_percorso);
}

//gestisce context menu della cronologia
void acetoneiso::historycontextmenu(const QPoint & posh)
{
  
QIcon mount_icon( ":/images/cdwriter_mount.png" );
QIcon delete_icon( ":/images/edit-delete.png" );

QMenu *userListMenuh;
userListMenuh = new QMenu();
QAction *mountActionh = userListMenuh->addAction( mount_icon,   tr("mount") );
QAction *deleteActionh = userListMenuh->addAction( delete_icon,  tr("delete") );

    QPoint globalPos = history->mapToGlobal(posh);    // Map the global position to the userlist
    QModelIndex t = history->indexAt(posh);
    //immagine_con_percorso variabile globale che contiene percorso immagine
    connect( mountActionh,    SIGNAL( triggered() ), this, SLOT( historycontextmenuMount() ) ); 
    connect( deleteActionh,   SIGNAL( triggered() ), this, SLOT( historycontextmenuDelete() ) );

    if( t.row() >= 0 ) { //previene un segfault se clicco col destro sullo spazio vuoto
       history->item(t.row())->setSelected(true);         // even a right click will select the item    
       immagine_con_percorso.clear();
       immagine_con_percorso = history->item(t.row())->text();
        QFileInfo image(immagine_con_percorso);
       QString image_no_path = image.fileName();
       mountActionh->setText(tr("mount") + " " +  image_no_path);
       deleteActionh->setText(tr("delete") + " " +  image_no_path);
       userListMenuh->exec(globalPos);
       }
}



//gestisco montaggio da context menu della cronologia
void acetoneiso::historycontextmenuMount() {
//controllo che esiste il file
QFile image_exists(immagine_con_percorso);
if (!image_exists.exists()) {
  QMessageBox::critical(this, "AcetoneISO",tr("The image ") + immagine_con_percorso  + tr(" doesn't exist.\nI'll remove it from history display."));
    int boot = 2;
    remove_non_images_history(boot);
  return;
  }  
global_functions_mount(immagine_con_percorso);
  
}

//gestisco cancella da context menu della cronologia
void acetoneiso::historycontextmenuDelete() {
QString oggetto(history->currentItem()->text() );//immagine selezionata 
QFile immagine_corrente( oggetto );

if (!immagine_corrente.exists()) {
  QMessageBox::critical(this, "AcetoneISO",tr("The image ") + oggetto  + tr(" doesn't exist.\nI'll remove it from history display."));
    int boot = 2;
    remove_non_images_history(boot);
  return;
  }  

QMessageBox msgBox;
msgBox.setText(tr("You are about to delete ") + oggetto + (" ") + tr("\nThis will remove it from history and fisically delete it.") + tr("\nAre You sure?"));
QPushButton *connectButton = msgBox.addButton(tr("Yes"), QMessageBox::ActionRole);
QPushButton *connectButton2 = msgBox.addButton(tr("No way!"), QMessageBox::ActionRole);
msgBox.exec();
 if (msgBox.clickedButton() == connectButton) {
	immagine_corrente.remove();
	int boot = 2;
	remove_non_images_history(boot);	
	}
 else if (msgBox.clickedButton() == connectButton2) {

}

	
  
}


//carico la cronologia
void acetoneiso::load_history() {
	history->clear();
	QDir Home = QDir::home();
	QFile history_conf(Home.path() + "/.acetoneiso/history.conf");
	history_conf.open(QIODevice::ReadOnly | QIODevice::Text);
	QTextStream history_out(&history_conf);
	int read_i = 0;
	while (true) {
	  QString history_line = history_out.readLine();
	  if (history_line == "") {
	    break;
	  }
	  history->insertItem(read_i, history_line);
	  //qDebug() << history_line;
	  read_i++;
	}
	
	history_conf.close();  
  
}


//gestisco l'autoclean della cronologia e rimozione automatica dei file inesistenti
void acetoneiso::history_autoclean() {
  
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("cleanhistory", Qt::CaseInsensitive)) {  
    QFile history_file(HomeT.path() + "/.acetoneiso/history.conf");
    history_file.remove();
    history->clear();
  }
  else {
   history_remove_nonexistant_images(); 
  }
  
fileT.close();  
}
//gestisce rimozione file inesistenti dalla cronologia. viene chiamato dalla funzione history_autoclean()
void acetoneiso::history_remove_nonexistant_images() {
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("removefakehistory", Qt::CaseInsensitive)) { 
    int boot = 0;
    remove_non_images_history(boot);
  }
 
fileT.close();  
}


//gestisce search della cronologia
void acetoneiso::search_history()
{
  
if( !search_history_lineedit->text().isEmpty() ) {  //se la lineEdit non è vuota
   int elements = history->count(); //numero totale di elementi nella lista
   int position = 0; 
//Nel ciclo while pongo come nascosti tutti gli elementi della lista
   while( position < elements ) {
      history->item( position )->setHidden(true);
      position = position +1;
      }
   QList<QListWidgetItem *> found(history->findItems( search_history_lineedit->text(), Qt::MatchContains )); //cerca gli elementi che contengono la stringa nel lineEdit
   QListWidgetItem*  item;
//in questo ciclo pongo come visibili solo gli elementi che contengono nel proprio nome la stringa che cerco.
   foreach (item, found ) {
        item->setHidden(false);
	}
   }
else {
  load_history();
   }
   
}


