/***************************************************************************
    copyright            : (C) 2001, 2006 by Mantia Andras
    email                : amantia@kdewebdev.org
 ***************************************************************************/

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

//own includes
#include "targetpath.h"
#include "kalleryglobals.h"

#include "kalleryfunctions.h"

//KDE includes
#include <kapplication.h>
#include <kiconloader.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kpushbutton.h>

//Qt includes
#include <qcheckbox.h>
#include <qlabel.h>
#include <qlineedit.h>

TargetPath::TargetPath(QWidget *parent, const char *name)
    :KTargetPathPage(parent, name)
{
  LogoPixmap->setPixmap(QPixmap(KalleryGlobals::ref()->baseDir() + "images/kallery.png", 0, QPixmap::Auto));

  GallerySelBtn->setIconSet(BarIconSet("fileopen"));
  ThumbDirSelBtn->setIconSet(BarIconSet("fileopen"));
  ImageDirSelBtn->setIconSet(BarIconSet("fileopen"));

  connect(ThumbDirSelBtn, SIGNAL(clicked()), this, SLOT(slotSelectThumbDir()));
  connect(ImageDirSelBtn, SIGNAL(clicked()), this, SLOT(slotSelectImageDir()));
  connect(GallerySelBtn, SIGNAL(clicked()), this, SLOT(slotSelectGalleryFile()));
}


void TargetPath::slotSelectThumbDir()
{
  selectDir(i18n("Select target thumbnail directory"),ThumbDirText,KalleryGlobals::ref()->options.thumbDestDir);
}


void TargetPath::slotSelectImageDir()
{
  selectDir(i18n("Select target image directory"),ImageDirText,KalleryGlobals::ref()->options.imageDestDir);
}


void TargetPath::slotSelectGalleryFile()
{
  QString tempStr;

  tempStr = KFileDialog::getOpenFileName(0,"*",this,i18n("Select gallery file directory and name"));
  if(!tempStr.isEmpty())
  {
    KalleryGlobals::ref()->options.galleryFile = tempStr;
  }
  GalleryText->setText(KalleryGlobals::ref()->options.galleryFile);
}

void TargetPath::invokeHelp()
{
  kapp->invokeHelp("targetpath-page","kallery");
}

bool TargetPath::processPage()
{
  /*Read the directory and file strings from the edit boxes*/
  KalleryGlobals::ref()->options.galleryFile = GalleryText->text();
  QString baseDir = QFileInfo(KalleryGlobals::ref()->options.galleryFile).dirPath() + "/";

  QString s = QDir::cleanDirPath(ThumbDirText->text());
  if (!s.startsWith("/"))
  {
    s.prepend(baseDir + "/");
  } 
  KalleryGlobals::ref()->options.thumbDestDir = s + "/";
  s = QDir::cleanDirPath(ImageDirText->text());
  if (!s.startsWith("/"))
  {
    s.prepend(baseDir + "/");
  } 
  KalleryGlobals::ref()->options.imageDestDir = s + "/";
  KalleryGlobals::ref()->setProjectBaseDir(baseDir);

  if ( (KalleryGlobals::ref()->options.thumbSetting == OptionType::GenerateThumbnails) && (KalleryGlobals::ref()->options.thumbDestDir == KalleryGlobals::ref()->options.imageDestDir) )
  {
    KMessageBox::error(this, i18n("The fullsize image and thumbnail destination directory cannot be the same!"), i18n("Error"));
    return false;
  }

  /*Create the missing directories and set the relative paths if needed */

  if ( !checkAndCreateDir(KalleryGlobals::ref()->projectBaseDir()) ||
       !checkAndCreateDir(KalleryGlobals::ref()->options.imageDestDir) ||
        ( (KalleryGlobals::ref()->options.thumbSetting == OptionType::GenerateThumbnails) && (!checkAndCreateDir(KalleryGlobals::ref()->options.thumbDestDir)) )||
        (KalleryGlobals::ref()->options.galleryFile == "") )
  {
    KMessageBox::error(this,i18n("The directories are invalid, or there is no gallery file specified!\n")+
                             i18n("Check them and try again."),i18n("Error"));
    return false;
  }

  KalleryGlobals::ref()->options.relativePaths = !AbsolutePaths->isChecked();

  return true;
}

void TargetPath::setupPage()
{
  ThumbDirLabel->setEnabled(KalleryGlobals::ref()->options.thumbSetting == OptionType::GenerateThumbnails);
  ThumbDirText->setEnabled(KalleryGlobals::ref()->options.thumbSetting == OptionType::GenerateThumbnails);
  ThumbDirSelBtn->setEnabled(KalleryGlobals::ref()->options.thumbSetting == OptionType::GenerateThumbnails);

  QString base = QFileInfo(KalleryGlobals::ref()->options.galleryFile).dirPath();
  GalleryText->setText(KalleryGlobals::ref()->options.galleryFile);
  QString s = KalleryGlobals::ref()->options.imageDestDir;
  KalleryFunctions::ref()->makeRelativePath(base, s);
  ImageDirText->setText(s);
  s = KalleryGlobals::ref()->options.thumbDestDir;
  KalleryFunctions::ref()->makeRelativePath(base, s);
  ThumbDirText->setText(s);
  AbsolutePaths->setChecked(!KalleryGlobals::ref()->options.relativePaths);
}

bool TargetPath::checkAndCreateDir(const QString& dirName )
{
  int pos;
  QString dirStr;
  QDir dir = QDir::root();
  dirStr = QDir::cleanDirPath(dirName);
  if  (!dir.cd(dirStr))
  {
    pos = dirStr.find("/",1);
/*    if (KMessageBox::questionYesNo(mainWidget,i18n("The directory %1 does not exists.\nDo you want to create it?").arg(dirName), i18n("Create directory")) == KMessageBox::Yes) */
    {
      while ( pos != -1)
      {
        dir.mkdir(dirStr.left(pos));
        pos = dirStr.find("/", pos+1);
      }
      dir.mkdir(dirStr);
      if (!dir.cd(dirName))
      {
        KMessageBox::error(this, i18n("The directory creation was unsuccesfull.\nPlease select another directory."), i18n("Error"));
        return false;
      }
    }/*
    else
    {
      return false;
    }*/
  }
  return true;
}

void TargetPath::selectDir(const QString &caption, QLineEdit *dirTextLine, QString& dirName)
{
  KFileDialog dirSelDlg(dirName, "*", this, "Opendir", true);
  QString selectedDir;

  selectedDir = dirSelDlg.getExistingDirectory(dirName, this, caption);

  if (! selectedDir.isEmpty())
  {
    dirTextLine->setText(selectedDir);
    dirName = selectedDir ;
  }
}

#include "targetpath.moc"
