/***************************************************************************
                          digikam.cpp  -  description
                             -------------------
    begin                : Wed Jan  9 18:01:17 CST 2002
    copyright            : (C) 2002 by Renchi Raju
    email                : renchi@green.tam.uiuc.edu
 ***************************************************************************/

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

#include <klocale.h>
#include <ktoolbar.h>
#include <kiconloader.h>
#include <kstddirs.h>
#include <kmessagebox.h>
#include <klistview.h>
#include <ksimpleconfig.h>
#include <kprogress.h>
#include <kfiledialog.h>
#include <kcombobox.h>
#include <kconfig.h>
#include <klineeditdlg.h>
#include <kaction.h>
#include <kstdaction.h>

#include <qpopupmenu.h>
#include <qwhatsthis.h>
#include <qcheckbox.h>
#include <qlayout.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qdir.h>
#include <qfileinfo.h>
#include <qfile.h>
#include <qwidgetstack.h>
#include <qtextview.h>
#include <qtimer.h>

#include "digikam.h"
#include "digikam_view.h"
#include "gphoto_interface.h"
#include "camera_folder.h"
#include "camera_iconview.h"
#include "camera_info.h"
#include "fileOp.h"
#include "setup.h"
#include "photo_folder.h"
#include "photo_foldertree.h"
#include "photo_iconview.h"
#include "image_lister.h"

Digikam::Digikam() : KMainWindow()
{
  
  config=kapp->config();

  initGlobals();
  initView();
  initToolBars();
  readOptions();

  gpInterface = new Gphoto_Interface(true);
  readConfig();
  setAbilitiesButtons();

  if (CONNECT_STARTUP) 
    slot_connect();

  setCamStatusMsg("Ready.");
  
}

Digikam::~Digikam()
{
  stopDownloading=true;
  delete gpInterface;

  delete imageLister;

  delete view;


}

void Digikam::initView()
{
  view = new Digikam_View(this, "mainView");
  setCentralWidget(view);

}


void Digikam::initToolBars()
{

  // Camera Browser Tool Bar

  toolBarCameraBrowser = new KToolBar(this,QMainWindow::Top , false, "CameraBrowser");
  toolBarCameraBrowser->show();

  camConnectAction = new KAction( i18n("Connect to camera"), "connect_established", 0,
				 this, SLOT(slot_connect()), this );
  camConnectAction->setWhatsThis( i18n("Establish Connection with the Camera") );
  
  camDownloadAction = new KToolBarPopupAction( i18n("Download Images"), "down", 0, 
				   this, SLOT(slot_downloadImages()), this );
  camDownloadAction->setWhatsThis( i18n("Download selected images from the Camera") );
  camDownloadAction->popupMenu()->insertItem( i18n("Download All"), 
					      this, SLOT(slot_downloadAllImages()), 0, 0 );

  camUploadAction = new KAction( i18n("Upload Images"), "up", 0, this );
  camUploadAction->setWhatsThis( i18n("Upload selected images into the Camera") );

  camDeleteAction = new KAction( i18n("Delete Images"), "trashcan_empty", 0,
				 this, SLOT(slot_deleteImages()), this );
  camDeleteAction->setWhatsThis( i18n("Delete selected images from the Camera") );

  camCancelAction = new KAction( i18n("Stop"), "stop", 0,
				 this, SLOT(slot_stopDownloadImages()), this );
  camCancelAction->setWhatsThis( i18n("Cancel Operations being Performed") );

  camSelectAction = new KToolBarPopupAction( i18n("Select Images"), "image", 0, this );
  camSelectAction->setWhatsThis( i18n("Make selections on the images") );
  camSelectAction->setDelayed(false);
  camSelectAction->popupMenu()->insertItem( i18n("Select All"), 0, 0);
  camSelectAction->popupMenu()->insertItem( i18n("Invert Selection"), 1, 1);
  camSelectAction->popupMenu()->insertItem( i18n("Select None"), 2, 2);  
  connect(camSelectAction->popupMenu(), SIGNAL(activated(int)), this, SLOT(slot_setCamSelection(int)));

  camMkFolderAction =  new KAction( i18n("Create Folder"), "folder_new", 0,
				 this, SLOT(slot_camMkFolder()), this);
  camMkFolderAction->setWhatsThis( i18n("Create a folder in the Camera") );

  camSetupAction = new KAction( i18n("Setup"), "configure", 0,
				 this, SLOT(slot_setup()), this);
  camSetupAction->setWhatsThis( i18n("Configure camera and other general settings") );

  camCameraInfoAction = new KAction( i18n("Camera Information"), "digikam", 0,
				 this, SLOT(slot_cameraInfo()), this);
  camCameraInfoAction->setWhatsThis( i18n("Retrieve Camera information") );

  appQuitAction = KStdAction::quit(this, SLOT(slot_close()), this);
  appQuitAction->setWhatsThis( i18n("Exit Application") );

  camConnectAction->plug(toolBarCameraBrowser);
  camDownloadAction->plug(toolBarCameraBrowser);
  camUploadAction->plug(toolBarCameraBrowser);
  camDeleteAction->plug(toolBarCameraBrowser);
  camCancelAction->plug(toolBarCameraBrowser);
  camSelectAction->plug(toolBarCameraBrowser);
  camMkFolderAction->plug(toolBarCameraBrowser);
  toolBarCameraBrowser->insertLineSeparator();
  camSetupAction->plug(toolBarCameraBrowser);
  camCameraInfoAction->plug(toolBarCameraBrowser);
  appQuitAction->plug(toolBarCameraBrowser);
  QWhatsThis::whatsThisButton(toolBarCameraBrowser);

  
  // Photo Browser Tool Bar

  toolBarPhotoBrowser = new KToolBar(this, QMainWindow::Top , false, "PhotoBrowser");
  toolBarPhotoBrowser->setIconSize(toolBarCameraBrowser->iconSize());
  toolBarPhotoBrowser->hide();
	

  photoHomeAction = KStdAction::home(this, SLOT(slot_photoGoHome()), actionCollection());
  photoHomeAction->setWhatsThis( i18n("Go to Home Directory") );

  photoCancelAction = new KAction( i18n("Stop"), "stop", 0,
				 this, SLOT(slot_stopGenThumbNails()), this );
  photoCancelAction->setWhatsThis( i18n("Stop Generating ThumbNails") );

  photoSmallThumbs=new KRadioAction(i18n("Small thumbnails"),"smallthumbnails", 0, 
				    this, SLOT(slot_setPhotoThumbSize()), this);
  photoSmallThumbs->setWhatsThis( i18n("Show small size thumbnails") );
  photoSmallThumbs->setExclusiveGroup("thumbnails");

  photoMedThumbs=new KRadioAction(i18n("Medium thumbnails"),"medthumbnails",0,
				  this, SLOT(slot_setPhotoThumbSize()), this);
  photoMedThumbs->setWhatsThis( i18n("Show medium size thumbnails") );
  photoMedThumbs->setExclusiveGroup("thumbnails");

  photoLargeThumbs=new KRadioAction(i18n("Large thumbnails"),"largethumbnails",0,
				    this, SLOT(slot_setPhotoThumbSize()), this);
  photoLargeThumbs->setWhatsThis( i18n("Show large size thumbnails") );
  photoLargeThumbs->setExclusiveGroup("thumbnails");

  photoHomeAction->plug(toolBarPhotoBrowser);
  photoCancelAction->plug(toolBarPhotoBrowser);
  photoSmallThumbs->plug(toolBarPhotoBrowser);
  photoMedThumbs->plug(toolBarPhotoBrowser);
  photoLargeThumbs->plug(toolBarPhotoBrowser);
  toolBarPhotoBrowser->insertSeparator();
  appQuitAction->plug(toolBarPhotoBrowser);
  QWhatsThis::whatsThisButton(toolBarPhotoBrowser);
  
  photoCancelAction->setEnabled(false);

}


void Digikam::initGlobals() {

  my_cameraFolder = "/";
  stopDownloading = false;

  // Photo Browser globals
  imageLister = new Image_Lister();        
  connect(imageLister, SIGNAL(newItems(const KFileItemList&)),
                this, SLOT(slot_newImageItems(const KFileItemList&)) );
  connect(imageLister, SIGNAL(clear()),
	  this, SLOT(slot_photoViewClear()) );
  connect(imageLister, SIGNAL(deleteItem(KFileItem*)),
	  this, SLOT(slot_deleteImageItem(KFileItem*)) );
  connect(imageLister, SIGNAL(completed()),
	  this, SLOT(slot_imageListerCompleted()) );
  connect(imageLister, SIGNAL(canceled()),
	  this, SLOT(slot_imageListerCanceled()) );
}


void Digikam::setAbilitiesButtons() {
  
  if (!(gpInterface->isCameraInitialised())) {
      camConnectAction->setEnabled(true);
      camDownloadAction->setEnabled(false);
      camUploadAction->setEnabled(false);
      camDeleteAction->setEnabled(false);
      camCancelAction->setEnabled(false);
      camSelectAction->setEnabled(false);
      camMkFolderAction->setEnabled(false);
      camCameraInfoAction->setEnabled(false);
      return;
  }
  
  camConnectAction->setEnabled(false);
  camDownloadAction->setEnabled(true);
  camSelectAction->setEnabled(true);
  camCameraInfoAction->setEnabled(true);

  if (!(gpInterface->cameraSupportsUpload()))                                                               
    camUploadAction->setEnabled(false); 
  else
    camUploadAction->setEnabled(true); 
  
  if (!(gpInterface->cameraSupportsDelete()))
    camDeleteAction->setEnabled(false);
  else
    camDeleteAction->setEnabled(true);
  
  if (!(gpInterface->cameraSupportsMkDir()))                                                            
    camMkFolderAction->setEnabled(false);
  else
    camMkFolderAction->setEnabled(true);
                                                                                                            
  //  if (!(gpInterface->cameraSupportsDelDir()))                                                               
  //  QPushButton_delFolder->setEnabled(false);                                                                 
                                                                                                            


  QString cameraModel, cameraPort;
  gpInterface->getCameraSettings(cameraModel, cameraPort);
  view->cameraLabel->setText(cameraModel + " (" + cameraPort + ")");

}


void Digikam::readOptions()
{
        
  config->setGroup("General Options");

  // camera bar position setting
  KToolBar::BarPosition camToolBarPos;
  camToolBarPos = (KToolBar::BarPosition) config->readNumEntry("CamToolBarPos", KToolBar::Top);
  toolBarCameraBrowser->setBarPos(camToolBarPos);
  
  // camera bar icon size setting
  int camToolBarIconSize;
  camToolBarIconSize = config->readNumEntry("CamToolBarIconSize", 22);
  toolBarCameraBrowser->setIconSize(camToolBarIconSize);

   // camera bar icon text setting
  KToolBar::IconText camToolBarIconText;
  camToolBarIconText = (KToolBar::IconText) config->readNumEntry("CamToolBarIconText", KToolBar::IconOnly);
  toolBarCameraBrowser->setIconText(camToolBarIconText);
    
  QSize size=config->readSizeEntry("Geometry");
  if(!size.isEmpty())
  {
    resize(size);
  }
}



void Digikam::saveOptions()
{       
  config->setGroup("General Options");
  config->writeEntry("Geometry", size());
  config->writeEntry("CamToolBarPos", (int) toolBarCameraBrowser->barPos());
  config->writeEntry("CamToolBarIconSize", toolBarCameraBrowser->iconSize());
  config->writeEntry("CamToolBarIconText", (int) toolBarCameraBrowser->iconText());
  config->writeEntry("PhotoToolBarPos", (int) toolBarCameraBrowser->barPos());
}


bool Digikam::queryExit()
{
  saveOptions();
  return true;
}


void Digikam::readConfig() {
  
  if (!(gpInterface->cameraSupportsThumbNails()))
    view->QCheckBox_thumbNails->setEnabled(false);
  else {
    view->QCheckBox_thumbNails->setEnabled(true);
    view->QCheckBox_thumbNails->setChecked(true);
  }

  KSimpleConfig* simpleConfig = new KSimpleConfig("digikamrc");
 
  simpleConfig->setGroup("General Settings");

  if (simpleConfig->readEntry("Default Download Directory") != NULL)
    DEFAULT_DOWNLOAD_DIR = simpleConfig->readEntry("Default Download Directory");
  if (DEFAULT_DOWNLOAD_DIR) {
    if (view->camDirBox->contains(DEFAULT_DOWNLOAD_DIR)) {
      for (int i = 0; i < view->camDirBox->count(); i++)
	if (DEFAULT_DOWNLOAD_DIR == view->camDirBox->text(i)) {
	  view->camDirBox->setCurrentItem(i);
	}
    }
    else {
      view->camDirBox->insertItem(DEFAULT_DOWNLOAD_DIR,0); 
    }
  }

 
  if (simpleConfig->readBoolEntry("No ThumbNails on Startup"))
    NO_THUMBNAIL_STARTUP = true;
  else
    NO_THUMBNAIL_STARTUP = false;

  if (view->QCheckBox_thumbNails->isEnabled()) {
    if (NO_THUMBNAIL_STARTUP)
      view->QCheckBox_thumbNails->setChecked(false);
    else
      view->QCheckBox_thumbNails->setChecked(true);
  }

  if (simpleConfig->readBoolEntry("Connect on Startup"))
    CONNECT_STARTUP=true;
  else
    CONNECT_STARTUP=false;

  if (simpleConfig->readBoolEntry("Show All Images on Startup"))
    SHOWALLIMAGES_STARTUP=true;
  else
    SHOWALLIMAGES_STARTUP=false;

  delete simpleConfig;

}



int Digikam::initCamera() {

  int retVal;

  if (!(gpInterface->isCameraInitialised())) {

    setCamStatusMsg("Initializing camera.");

    retVal = gpInterface->initCamera();

    if (retVal != 0) {

      if (retVal == -1)
        KMessageBox::error(this,"Camera Model or Port Setting\n"
                         "not specified correctly!\n"
                         "Please, run Setup");
      else if (retVal == -2)
        KMessageBox::error(this,"Failed to initialize camera!\n"
                           "Make sure the camera is connected\n"
                       "properly and powered on.");
      else
        KMessageBox::error(this,"Unknown Error!");

      return -1;
    }

    setCamStatusMsg("Camera Initialized");

  }

  return 0;

}


int Digikam::getFolderNames(Camera_Folder* camFolder) {

  QStringList subFolderList;
  QStringList subFolderNameList;
  int numSubFolders;
  QString folder;

  subFolderList.clear();
  subFolderNameList.clear();
  numSubFolders = 0;
  folder = camFolder->getPath();

  if (gpInterface->getSubFolders(folder, subFolderList,
                                 subFolderNameList, numSubFolders) == -1) {
    KMessageBox::error(this, "Failed to get SubFolder names\n"
                       "Check if camera is disconnected.");
    return -1;
  }


  for (int i=0; i<numSubFolders; i++) {

    Camera_Folder *camFolderChild = new Camera_Folder(camFolder, subFolderList[i],
                                                     subFolderNameList[i]);
    camFolderChild->iconView = new Camera_IconView(view->QWidgetStack_camIconViews);
    view->QWidgetStack_camIconViews->addWidget(camFolderChild->iconView, ++(view->QWidgetStack_id));

    getFolderNames(camFolderChild);

  }

  return 0;

}

int Digikam::getIcons() {

  Camera_Folder *camFolder;
  QStringList imagesList;
  QStringList imagesInfoList;

  imagesList.clear();
  imagesInfoList.clear();

  QListViewItemIterator it(view->KListView_camFolders);
  for ( ; it.current(); ++it ) {

    camFolder = (Camera_Folder*) (it.current());
    if (camFolder == view->camGlobFolder) continue;

    if (gpInterface->getImageNames(camFolder->getPath(), imagesList, imagesInfoList)
        == -1) {
      KMessageBox::error(this, "Failed to get Image Names\n"
                         "Check if camera is disconnected.");
      return -1;
    }

    for (int i=0; i<imagesList.count(); i++) {
      
      if ((imagesInfoList[i]).contains("image") || (imagesInfoList[i]).contains("audio")
          || (imagesInfoList[i]).contains("video")) {

        Camera_IconViewItem* item = new Camera_IconViewItem(camFolder->iconView);
        item->setText(imagesList[i]);
        item->setMimeType(imagesInfoList[i]);
	item->setCameraFolder(camFolder->getPath());

        if ( view->QCheckBox_thumbNails->isChecked() && (imagesInfoList[i]).contains("image") ) {
          item->setThumbNail(gpInterface->getThumbNail(item->getCameraFolder(), imagesList[i]));
        }
        else {
          item->setPixmapForMime();
        }
	
	insertIconGlobal(item);
	syncIconGlobal(item);
      }
    }

    camFolder->setCount(imagesList.count());
  }

  view->camGlobFolder->setCount(view->camGlobFolder->iconView->count());
  
  return 0;

}


void Digikam::insertIconGlobal(Camera_IconViewItem* item) {

  if (!item) return;
  Camera_IconViewItem* itemGlob = new Camera_IconViewItem(view->camGlobFolder->iconView);
  item->itemInGlobal = itemGlob;
  itemGlob->itemInGlobal = item;
}

void Digikam::syncIconGlobal(Camera_IconViewItem* item) {

  if (!item) return;
  Camera_IconViewItem* itemGlob = item->itemInGlobal;
  if (!itemGlob) return;

  itemGlob->setText ( item->text() );
  itemGlob->setMimeType( item->getMimeType() );
  itemGlob->setCameraFolder( item->getCameraFolder() );
  itemGlob->setPixmap( *(item->pixmap()) );
    
  view->camGlobFolder->iconView->arrangeItemsInGrid();   
}

void Digikam::removeIconGlobal(Camera_IconViewItem* item) {
  
  if (!item) return;
  Camera_IconViewItem* itemGlob = item->itemInGlobal;
  if (!itemGlob) return;
  delete itemGlob;

  view->camGlobFolder->iconView->arrangeItemsInGrid();

}



void Digikam::setCamStatusMsg(const QString &msg) {

  view->camStatusBar->changeItem(msg,0);

}


void Digikam::restoreCamButtons() {

  camDownloadAction->setEnabled(true);

  if (!(gpInterface->cameraSupportsUpload()))                                                               
    camUploadAction->setEnabled(false); 
  else
    camUploadAction->setEnabled(true); 


  if (!(gpInterface->cameraSupportsDelete()))
    camDeleteAction->setEnabled(false);
  else
    camDeleteAction->setEnabled(true);

  camCancelAction->setEnabled(false);
  
  if (!(gpInterface->cameraSupportsMkDir()))                                                            
    camMkFolderAction->setEnabled(false);                                                                
  else
    camMkFolderAction->setEnabled(true);

  camSelectAction->setEnabled(true);
  camSetupAction->setEnabled(true);  
  camCameraInfoAction->setEnabled(true);
  appQuitAction->setEnabled(true);

  //  if (!(gpInterface->cameraSupportsDelDir()))                                                               
  //  QPushButton_delFolder->setEnabled(false);                                                                 
                                                                                                            

}


void Digikam::slot_showHideToolBars(QWidget* tab)
{
  if (tab == view->tabCameraBrowser) {
    toolBarCameraBrowser->show();
    toolBarPhotoBrowser->hide();
  }
  else {
    toolBarCameraBrowser->hide();
    toolBarPhotoBrowser->show();
  }
}

void Digikam::slot_connect() {
  
  if (initCamera()!=0)  {
    setCamStatusMsg("Abort.");
    return;
  }

  view->QWidgetStack_id=0;
  view->QWidgetStack_camIconViews->raiseWidget(0);

  view->KListView_camFolders->clear();
  Camera_Folder *camFolder = new Camera_Folder(view->KListView_camFolders, my_cameraFolder,
                                               my_cameraFolder);
  camFolder->iconView = new Camera_IconView(view->QWidgetStack_camIconViews);
  view->QWidgetStack_camIconViews->addWidget(camFolder->iconView, ++(view->QWidgetStack_id));


  // Global Folder
  view->camGlobFolder = new Camera_Folder(view->KListView_camFolders, "Global",
						   "Global");
  view->camGlobFolder->iconView = new Camera_IconView(view->QWidgetStack_camIconViews);
  view->QWidgetStack_camIconViews->addWidget(view->camGlobFolder->iconView, ++(view->QWidgetStack_id));


  if (getFolderNames(camFolder) == -1) {
    setCamStatusMsg("Abort.");
    gpInterface->setCameraInitialised(false);
    return;
  }

  if (getIcons() == -1) {
    setCamStatusMsg("Abort.");
    gpInterface->setCameraInitialised(false);
    return;
  }

  setAbilitiesButtons();

  
  if (SHOWALLIMAGES_STARTUP) {
    slot_camFolderViewClicked(view->camGlobFolder);
    view->KListView_camFolders->setSelected(view->camGlobFolder, true);
  }
  else {
    slot_camFolderViewClicked(view->KListView_camFolders->firstChild());
    view->KListView_camFolders->setSelected(view->KListView_camFolders->firstChild(), true);
  }



}


void Digikam::slot_camFolderViewClicked(QListViewItem *item) {
  
  if ( !item )
    return;

  Camera_Folder* cf=(Camera_Folder*)item;
  view->QWidgetStack_camIconViews->raiseWidget(cf->iconView);

  if ((cf->isOpen()))
    cf->setOpen(false);
  else
    cf->setOpen(true);

  qWarning(cf->getPath() + " folder clicked");

}


void Digikam:: slot_getThumbNails(bool checked) 
{

  // First check if camera is initialised
  
  if ( !( gpInterface->isCameraInitialised() ) )
    return;

  Camera_Folder *camFolder= (Camera_Folder*) view->KListView_camFolders->firstChild();
  if (camFolder==NULL) return;

  Camera_IconView* iconView;

  QListViewItemIterator it(view->KListView_camFolders);
  for ( ; it.current(); ++it ) {

    camFolder = (Camera_Folder*) (it.current());
    if (camFolder == view->camGlobFolder) continue;
    iconView = camFolder->iconView;

    if (checked) {
    
      Camera_IconViewItem* item = (Camera_IconViewItem*) iconView->firstItem();

      while (item) {

	QString mime;
	mime = item->getMimeType();
	
	if (mime.contains("image")) {
	  if ( !(item->isThumbNailed()) ) {
	    item->setThumbNail(gpInterface->getThumbNail(item->getCameraFolder(), item->text()));
	  }
	  else
	    item->setThumbNail();
	}
	syncIconGlobal(item);
	item = (Camera_IconViewItem*) item->nextItem();

      }

      iconView->arrangeItemsInGrid(); 

    }
    else {

      Camera_IconViewItem* item = (Camera_IconViewItem*) iconView->firstItem();
      
      while (item) {
      
	item->setPixmapForMime();
	syncIconGlobal(item);
	item = (Camera_IconViewItem*) item->nextItem();

      }

      iconView->arrangeItemsInGrid(); 

    }
  
  }
  
}
  

void Digikam:: slot_downloadImages() 
{

  // First check if camera is initialised
  
  if ( !( gpInterface->isCameraInitialised() ) )
    return;

  Camera_Folder *camFolder= (Camera_Folder*) view->KListView_camFolders->firstChild();
  if (camFolder==NULL) return;


  camUploadAction->setEnabled(false);
  camDownloadAction->setEnabled(false);
  camDeleteAction->setEnabled(false);
  camCancelAction->setEnabled(true);
  camMkFolderAction->setEnabled(false);
  camSelectAction->setEnabled(false);
  camSetupAction->setEnabled(false);
  camCameraInfoAction->setEnabled(false);
  appQuitAction->setEnabled(false);

  Camera_IconView* iconView = (Camera_IconView*) view->QWidgetStack_camIconViews->visibleWidget();

  QListViewItemIterator it(view->KListView_camFolders);
  for ( ; it.current(); ++it ) {

    camFolder = (Camera_Folder*) (it.current());
    
    if (camFolder->iconView == iconView) 
      break;

  }

  qWarning("Downloading from: " + camFolder->getPath());


  int j = 0;
  for ( QIconViewItem *i = iconView->firstItem(); i; i = i->nextItem() )
    if (i->isSelected()) ++j;
  if (j == 0) {
    KMessageBox::error(this,"No images selected!");
    restoreCamButtons();
    return;
  }


  QString downloadDir=view->camDirBox->currentText();
  QString saveFile;

  if ( downloadDir != "/" && (downloadDir.right(1) == "/") )
    downloadDir = downloadDir.left(downloadDir.length()-1);

  QDir dir(downloadDir);
  if (!dir.exists()) {
    KMessageBox::error(this, downloadDir + " does not exist!");
    restoreCamButtons();
    return;
  }

  setCamStatusMsg("Starting Downloads ...");

  bool overwriteallmode=false;
  bool skipallmode=false;
  bool savefilemode=true;

  stopDownloading = false;

  for ( QIconViewItem *i = iconView->firstItem(); i; i = i->nextItem() ) {

    if (skipallmode) break;

    if (i->isSelected()) {

      saveFile=downloadDir + "/" + i->text();
      qWarning(saveFile);

      while (QFile::exists(saveFile) && !(overwriteallmode)) {

	FileOpDialog *dlg = new FileOpDialog(saveFile, saveFile, NULL, NULL);

	if (dlg->exec()== QDialog::Rejected){
	  restoreCamButtons();
	  setCamStatusMsg("Abort");
	  view->camProgressBar->setValue(0);
	  view->camProgressBar->repaint();
	  delete dlg;
	  return;
	}

	if (dlg->fileOpSelection() == Skip) {
	  qWarning("Skipped.");
	  delete dlg;
	  savefilemode=false;
	  break;
	} 
	else if (dlg->fileOpSelection() == SkipAll) {
	  qWarning("Skipped All.");
	  skipallmode=true;
	  savefilemode=false;
	  delete dlg;
	  break;
	} 
	else if (dlg->fileOpSelection() == Overwrite) {
	  qWarning("Overwrite.");	  
	  delete dlg;
	  savefilemode=true;
	  break;
	}
	else if (dlg->fileOpSelection() == OverwriteAll) {
	  qWarning("Overwrite All.");	  
	  delete dlg;
	  savefilemode=true;
	  overwriteallmode=true;
	  break; 
	}
	else if (dlg->fileOpSelection() == Rename) {
	  qWarning("Rename.");
	  savefilemode=true;
	  saveFile = downloadDir+"/"+dlg->renameString();
	  delete dlg;
	  qWarning(saveFile+" - New Name");
	}

      }

      if (stopDownloading) return;
      
      if (savefilemode) {
	Camera_IconViewItem *item = (Camera_IconViewItem *) i;
	if ((gpInterface->downloadImage(item->getCameraFolder(), 
					  item->text(), saveFile)) < 0) {
	  KMessageBox::error(this,"Failed to save images!");
	  restoreCamButtons();
	  setCamStatusMsg("Abort");
	  view->camProgressBar->setValue(0);
	  view->camProgressBar->repaint();
	  return;
	}
      }
      kapp->processEvents();
      savefilemode=true;
    }

  }
  
  restoreCamButtons();
  setCamStatusMsg("Finished Downloads");
  view->camProgressBar->setValue(0);
  view->camProgressBar->repaint();
}



void Digikam::slot_downloadAllImages()
{

  // First check if camera is initialised
  
  if ( !( gpInterface->isCameraInitialised() ) )
    return;

  Camera_Folder *camFolder= (Camera_Folder*) view->KListView_camFolders->firstChild();
  if (camFolder==NULL) return;

  camUploadAction->setEnabled(false);
  camDownloadAction->setEnabled(false);
  camDeleteAction->setEnabled(false);
  camCancelAction->setEnabled(true);
  camMkFolderAction->setEnabled(false);
  camSelectAction->setEnabled(false);
  camSetupAction->setEnabled(false);
  camCameraInfoAction->setEnabled(false);
  appQuitAction->setEnabled(false);


  QString downloadDir=view->camDirBox->currentText();
  QString saveFile;

  if ( downloadDir != "/" && (downloadDir.right(1) == "/") )
    downloadDir = downloadDir.left(downloadDir.length()-1);

  QDir dir(downloadDir);
  if (!dir.exists()) {
    KMessageBox::error(this, downloadDir + " does not exist!");
    restoreCamButtons();
    return;
  }

  setCamStatusMsg("Downloading ...");

  Camera_IconView* iconView;
  bool overwriteallmode=false;
  bool skipallmode=false;
  bool savefilemode=true;
  stopDownloading = false;

  QListViewItemIterator it(view->KListView_camFolders);
  for ( ; it.current(); ++it ) {

    camFolder = (Camera_Folder*) (it.current());
    if (camFolder == view->camGlobFolder) continue;
    qWarning("Downloading from: " + camFolder->getPath());
    
    iconView = camFolder->iconView;
    if (iconView->count() == 0) continue;
    
    for ( QIconViewItem *i = iconView->firstItem(); i; i = i->nextItem() ) {

      if (skipallmode) break;

      saveFile=downloadDir + "/" + i->text();
      qWarning(saveFile);

      while (QFile::exists(saveFile) && !(overwriteallmode)) {

	FileOpDialog *dlg = new FileOpDialog(saveFile, saveFile, NULL, NULL);

	if (dlg->exec()== QDialog::Rejected){
	  restoreCamButtons();
	  setCamStatusMsg("Abort");
	  view->camProgressBar->setValue(0);
	  view->camProgressBar->repaint();
	  delete dlg;
	  return;
	}

	if (dlg->fileOpSelection() == Skip) {
	  qWarning("Skipped.");
	  delete dlg;
	  savefilemode=false;
	  break;
	} 
	else if (dlg->fileOpSelection() == SkipAll) {
	  qWarning("Skipped All.");
	  skipallmode=true;
	  savefilemode=false;
	  delete dlg;
	  break;
	} 
	else if (dlg->fileOpSelection() == Overwrite) {
	  qWarning("Overwrite.");	  
	  delete dlg;
	  savefilemode=true;
	  break;
	}
	else if (dlg->fileOpSelection() == OverwriteAll) {
	  qWarning("Overwrite All.");	  
	  delete dlg;
	  savefilemode=true;
	  overwriteallmode=true;
	  break; 
	}
	else if (dlg->fileOpSelection() == Rename) {
	  qWarning("Rename.");
	  savefilemode=true;
	  saveFile = downloadDir+"/"+dlg->renameString();
	  delete dlg;
	  qWarning(saveFile+" - New Name");
	}

      }

      if (stopDownloading) return;
      
      if (savefilemode) {
	Camera_IconViewItem *item = (Camera_IconViewItem *) i;
	if ((gpInterface->downloadImage(item->getCameraFolder(), 
					  item->text(), saveFile)) < 0) {
	  KMessageBox::error(this,"Failed to save images!");
	  restoreCamButtons();
	  setCamStatusMsg("Abort");
	  view->camProgressBar->setValue(0);
	  view->camProgressBar->repaint();
	  return;
	}
      }
      kapp->processEvents();
      savefilemode=true;
    }

    
    
  }

  restoreCamButtons();
  setCamStatusMsg("Finished Downloads");
  view->camProgressBar->setValue(0);
  view->camProgressBar->repaint();

}




void Digikam::slot_stopDownloadImages()
{

  stopDownloading = true;
  restoreCamButtons();

  setCamStatusMsg("Aborted");
  view->camProgressBar->setValue(0);
  view->camProgressBar->repaint();

}
  

void Digikam::slot_deleteImages()
{
  // First check if camera is initialised
  
  if ( !( gpInterface->isCameraInitialised() ) )
    return;

  Camera_IconView* iconView = (Camera_IconView*) view->QWidgetStack_camIconViews->visibleWidget();
  Camera_Folder *camFolder = (Camera_Folder*) view->KListView_camFolders->firstChild();

  if (camFolder==NULL) return;

  QListViewItemIterator it(view->KListView_camFolders);
  for ( ; it.current(); ++it ) {
    camFolder = (Camera_Folder*) (it.current());
    if (camFolder->iconView == iconView) 
      break;
  }

  qWarning("Deleting from: " + camFolder->getPath());

  int j = 0;
  QStringList imageList;
  for ( QIconViewItem *i = iconView->firstItem(); i; i = i->nextItem() ) {
    if (i->isSelected()) {
      imageList.append(i->text());
      ++j;
    }
  }

  if (j == 0) {
    KMessageBox::error(this,"No images selected!");
    return;
  }


  Camera_IconViewItem *item;

  if (KMessageBox::warningContinueCancelList(this, "About to delete these Image(s)\n"
					     "Are you sure?",imageList, "Warning",
					     "Delete") ==  KMessageBox::Continue) {
    
    item = (Camera_IconViewItem*) iconView->firstItem();
    while (item) {
      
      Camera_IconViewItem *nextItem = (Camera_IconViewItem*) item->nextItem();

      if (item->isSelected()) {
	if (gpInterface->deleteImage(item->getCameraFolder(), item->text()) < 0) {
	  KMessageBox::error(this,"Failed to delete images!");
	  return;
	}
	removeIconGlobal(item);
	delete item;
	iconView->arrangeItemsInGrid();
      }
      item = nextItem;
      
    }
  
  }    

  QListViewItemIterator it2(view->KListView_camFolders);
  for ( ; it2.current(); ++it2 ) {
    camFolder = (Camera_Folder*) (it2.current());
    camFolder->setCount(camFolder->iconView->count());
  }

}


void Digikam::slot_camMkFolder() 
{

  // First check if camera is initialised
  if ( !( gpInterface->isCameraInitialised() ) ) return;

  Camera_Folder* camFolder = (Camera_Folder*) view->KListView_camFolders->selectedItem();
  if (!camFolder) return;
  
  if (camFolder->getName() == "Global") {
    KMessageBox::error(this,"Cannot create directory in Global Folder");
    return;
  }



  QString newFolder;
  bool ok;

  newFolder = KLineEditDlg::getText ("Create a New Folder in " + camFolder->getPath(), 
				     "NewDirectory", &ok, this);
  if (ok && !(newFolder.isEmpty())) {
    if (gpInterface->makeDir(camFolder->getPath(), newFolder) != 0) {
      KMessageBox::error(this,"Failed to create Directory");
      return;
    }
    else {
      QString newFolderPath;
      if (camFolder->getPath() != "/")
	newFolderPath = camFolder->getPath() + "/" + newFolder;
      else
	newFolderPath = camFolder->getPath() + newFolder;
      Camera_Folder *camFolderChild = new Camera_Folder(camFolder, newFolderPath, newFolder);
      camFolderChild->iconView = new Camera_IconView(view->QWidgetStack_camIconViews);
      view->QWidgetStack_camIconViews->addWidget(camFolderChild->iconView, ++(view->QWidgetStack_id));
      camFolderChild->setCount(camFolderChild->iconView->count());
    }
      
  }
  return;
    
  

}


void Digikam::slot_setCamSelection(int selectMode) 
{
  Camera_IconView* iconView = (Camera_IconView*) (view->QWidgetStack_camIconViews->visibleWidget());

  if (selectMode == 0) {
    iconView->selectAll(true);
  }
  else if (selectMode == 1) {
    iconView->invertSelection();
  }
  else if (selectMode == 2) {
    iconView->selectAll(false);
  }
}

  
void Digikam::slot_camDirBrowse() {

  QString result = 
    KFileDialog::getExistingDirectory( view->camDirBox->text(view->camDirBox->currentItem()),
				       this );
  if (!result.isEmpty()) {
    for (int i = 0; i < view->camDirBox->count(); i++)
      if (result == view->camDirBox->text(i)) {
	view->camDirBox->setCurrentItem(i);
	return;
      }
    view->camDirBox->insertItem(result, 0);
    view->camDirBox->setCurrentItem(0);
  }
  
}

void Digikam::slot_close()
{
  saveOptions();
  delete this;
}


void Digikam::slot_cameraInfo() {
  
  if (gpInterface->isCameraInitialised()) {

    QString summary;
    gpInterface->getCameraSummary(summary);
    
    QString manual;
    gpInterface->getCameraManual(manual);

    QString about;
    gpInterface->getCameraAbout(about);

    Camera_Info* cameraInfo = new Camera_Info;
    cameraInfo->QTextView_summary->setText(summary);
    cameraInfo->QTextView_manual->setText(manual);
    cameraInfo->QTextView_about->setText(about);    
    cameraInfo->show();

  }

}

void Digikam::slot_setup()
{
  QString cameraModel, cameraPort;
  QString cameraModelNew, cameraPortNew;

  gpInterface->getCameraSettings(cameraModel, cameraPort);

  Setup *setup=new Setup();
  setup->show();

  gpInterface->getCameraSettings(cameraModelNew, cameraPortNew);

  if ((cameraModel != cameraModelNew) || (cameraPort != cameraPortNew)) {
    delete gpInterface;
    gpInterface = new Gphoto_Interface(true);
    setAbilitiesButtons();
    view->QWidgetStack_id=0;
    view->QWidgetStack_camIconViews->raiseWidget(0);
    view->KListView_camFolders->clear();
  }

  readConfig();
}


void Digikam::slot_photoFolderClicked(QListViewItem *item) 
{
  if (!item) return;
  Photo_Folder* photoFolder = (Photo_Folder*) item;

  view->photoFolderTree->setFolder(photoFolder);
  
  view->photoIconView->stopGenThumbnail();
  imageLister->openURL(photoFolder->getURL(), true);
}


void Digikam::slot_newImageItems(const KFileItemList& fileItemList) 
{
  view->photoIconView->addItemList(fileItemList);
}

void Digikam::slot_deleteImageItem(KFileItem* item)
{
  view->photoIconView->removeItem((KFileViewItem*)item);
}

void Digikam::slot_photoViewClear()
{
  ((KFileView*) view->photoIconView)->clear();
}


void Digikam::slot_imageListerCompleted() 
{
  view->photoIconView->startGenThumbnail();
}

void Digikam:: slot_imageListerCanceled()
{
  view->photoIconView->stopGenThumbnail();
}

void Digikam::slot_photoGoHome() {

  view->photoIconView->stopGenThumbnail();
  view->photoFolderTree->setSelected(view->photoFolderTree->firstChild(), true);
  view->photoFolderTree->ensureItemVisible(view->photoFolderTree->firstChild());
  imageLister->openURL(KURL("file:"+QDir::homeDirPath()), true);

}


void Digikam::slot_setPhotoThumbSize() {

  if (photoSmallThumbs->isChecked()) 
    view->photoIconView->setThumbSize(ThumbnailSize::Small);
  else if (photoMedThumbs->isChecked()) 
    view->photoIconView->setThumbSize(ThumbnailSize::Med);
  else if (photoLargeThumbs->isChecked()) 
    view->photoIconView->setThumbSize(ThumbnailSize::Large);

  view->photoIconView->stopGenThumbnail();
  imageLister->listDirectory();
}

void Digikam::slot_stopGenThumbNails() {
  view->photoIconView->stopGenThumbnail();
}

void Digikam::slot_startedGenThumbNails() {
  photoCancelAction->setEnabled(true);
}

void Digikam::slot_stoppedGenThumbNails() {
  photoCancelAction->setEnabled(false);
}

