//
// C++ Implementation: $MODULE$
//
// Description:
//
//
// Author: Andras Mantia <amantia@kdewebdev.org>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//

//own includes
#include "htmloptionspage.h"
#include "kalleryglobals.h"
#include "kalleryfunctions.h"

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

//Qt includes
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qregexp.h>
#include <qspinbox.h>
#include <qtoolbutton.h>

HtmlOptionsPage::HtmlOptionsPage(QWidget *parent, const char *name)
    :KHtmlOptionsPage(parent, name)
{
  LogoPixmap->setPixmap(QPixmap(KalleryGlobals::ref()->baseDir() + "images/kallery.png",0,QPixmap::Auto));
  BackColorBtn->setIconSet(BarIconSet("colorize"));
  TextColorBtn->setIconSet(BarIconSet("colorize"));
  TableColorBtn->setIconSet(BarIconSet("colorize"));
  VisitedColorBtn->setIconSet(BarIconSet("colorize"));
  BeforeHtmlSelBtn->setIconSet(BarIconSet("fileopen"));
  AfterHtmlSelBtn->setIconSet(BarIconSet("fileopen"));
  GalleryCSSSelBtn->setIconSet(BarIconSet("fileopen"));

  connect(TableColorBtn, SIGNAL(clicked()), this, SLOT(slotSelectTableColor()));
  connect(BackColorBtn, SIGNAL(clicked()), this, SLOT(slotSelectBackColor()));
  connect(TextColorBtn, SIGNAL(clicked()), this, SLOT(slotSelectTextColor()));
  connect(VisitedColorBtn, SIGNAL(clicked()), this, SLOT(slotSelectVisitedColor()));
  connect(GalleryCSSSelBtn, SIGNAL(clicked()), this, SLOT(slotSelectGalleryCSS()));
  connect(BeforeHtmlSelBtn, SIGNAL(clicked()), this, SLOT(slotSelectBeforeHtml()));
  connect(AfterHtmlSelBtn, SIGNAL(clicked()), this, SLOT(slotSelectAfterHtml()));
  connect(GalleryTemplateCombo, SIGNAL(activated(int)), this, SLOT(slotTemplateChanged(int)));
  loadTemplates();
}


void HtmlOptionsPage::slotSelectTableColor()
{
  QColor tmpColor = KalleryGlobals::ref()->options.tableColor;

  KColorDialog::getColor(tmpColor, this);
  TableColorFrame->setBackgroundColor(tmpColor);
}


void HtmlOptionsPage::slotSelectBackColor()
{
  QColor tmpColor = KalleryGlobals::ref()->options.backColor;

  KColorDialog::getColor(tmpColor, this);
  BackColorFrame->setBackgroundColor(tmpColor);
}


void HtmlOptionsPage::slotSelectTextColor()
{
  QColor tmpColor = KalleryGlobals::ref()->options.textColor;

  KColorDialog::getColor(tmpColor, this);
  TextColorFrame->setBackgroundColor(tmpColor);
}

void HtmlOptionsPage::slotSelectVisitedColor()
{
  QColor tmpColor = KalleryGlobals::ref()->options.visitedColor;
  KColorDialog::getColor(tmpColor, this);
  VisitedColorFrame->setBackgroundColor(tmpColor);
}


void HtmlOptionsPage::slotSelectGalleryCSS()
{
  QString tempStr;

  tempStr = KFileDialog::getOpenFileName(0,"*",this,i18n("Select the CSS file"));
  if(!tempStr.isEmpty()) {KalleryGlobals::ref()->options.galleryCSSFile = tempStr;}
  OwnGalleryCSSName->setText(KalleryGlobals::ref()->options.galleryCSSFile);
}


void HtmlOptionsPage::slotSelectBeforeHtml()
{
  QString tmpString;

  tmpString = KFileDialog::getOpenFileName("","*",this,i18n("Select a html formatted text file"));
  if (!tmpString.isEmpty())
  {
    BeforeHtmlEdit->setText(tmpString);
  }
}


void HtmlOptionsPage::slotSelectAfterHtml()
{
  QString tmpString;

  tmpString = KFileDialog::getOpenFileName("","*",this,i18n("Select a html formatted text file"));
  if (!tmpString.isEmpty())
  {
    AfterHtmlEdit->setText(tmpString);
  }
}

void HtmlOptionsPage::invokeHelp()
{
  kapp->invokeHelp("htmloptions-page","kallery");
}

bool HtmlOptionsPage::processPage()
{
  KalleryGlobals::ref()->options.galleryTitle = PageTitleEdit->text();
  KalleryGlobals::ref()->options.language = GalleryLanguageCombo->currentText();
  int i = GalleryTemplateCombo->currentItem();
  KalleryGlobals::ref()->options.galleryTemplateFile = galleryTemplateList[i].left(galleryTemplateList[i].find('|'));
  KalleryGlobals::ref()->options.galleryTemplate =  GalleryTemplateCombo->currentText();
  KalleryGlobals::ref()->options.columnNum =  ColumnNumSpinBox->value();
  KalleryGlobals::ref()->options.tableColor = TableColorFrame->backgroundColor();
  KalleryGlobals::ref()->options.backColor = BackColorFrame->backgroundColor();
  KalleryGlobals::ref()->options.textColor = TextColorFrame->backgroundColor();
  KalleryGlobals::ref()->options.visitedColor = VisitedColorFrame->backgroundColor();
  KalleryGlobals::ref()->options.encoding = EncodingCombo->currentText();

  if (UseGalleryCSS->isChecked())
  {
    KalleryGlobals::ref()->options.galleryCSSFile = OwnGalleryCSSName->text();
    if (!QFileInfo(KalleryGlobals::ref()->options.galleryCSSFile).exists())
    {
      if (KMessageBox::warningYesNo(this,i18n("The file %1 is missing. Continue anyway?").arg(KalleryGlobals::ref()->options.galleryCSSFile),i18n("Missing file")) == KMessageBox::No)
      {
        return false;
      }
    }
  }
  else
  {
    KalleryGlobals::ref()->options.galleryCSSFile = "";
  }

  KalleryGlobals::ref()->options.beforeHtmlFile =  BeforeHtmlEdit->text();
  KalleryGlobals::ref()->options.afterHtmlFile =  AfterHtmlEdit->text();

  //Check the existance of the selected files.
  if ((!KalleryGlobals::ref()->options.beforeHtmlFile.isEmpty()) && (!QFileInfo(KalleryGlobals::ref()->options.beforeHtmlFile).exists()))
  {
    if (KMessageBox::warningYesNo(this,i18n("The file %1 is missing. Continue anyway?").arg(KalleryGlobals::ref()->options.beforeHtmlFile),i18n("Missing file")) == KMessageBox::No)
    {
       return false;
    }
  }
  if ((!KalleryGlobals::ref()->options.afterHtmlFile.isEmpty()) && (!QFileInfo(KalleryGlobals::ref()->options.afterHtmlFile).exists()))
  {
    if (KMessageBox::warningYesNo(this,i18n("The file %1 is missing. Continue anyway?").arg(KalleryGlobals::ref()->options.afterHtmlFile),i18n("Missing file")) == KMessageBox::No)
    {
       return false;
    }
  }

  if ((KalleryGlobals::ref()->options.galleryTemplateFile.find("gallery_frame.template") == -1) &&
    (KalleryGlobals::ref()->options.useFrames))
  {
    if (KMessageBox::warningYesNo(this,i18n("You have selected to use frames, but a non frame template. This is not good.\n Continue anyway?"),i18n("Settings missmatch")) == KMessageBox::No)
    {
      return false;
    }
  }

  return true;
}

void HtmlOptionsPage::setupPage()
{
//FIXME: This should load the list of languages, and not the list of countries!!
  loadCountryList(GalleryLanguageCombo);
  for (int i = 0; i < GalleryLanguageCombo->count(); i++)
  {
    GalleryLanguageCombo->setCurrentItem(i);
    if (GalleryLanguageCombo->currentText() == KalleryGlobals::ref()->options.language)
    {
      break;
    }
  }

  GalleryTemplateCombo->clear();
  for (uint i = 0; i < galleryTemplateList.count(); i++)
  {
    GalleryTemplateCombo->insertItem(galleryTemplateList[i].mid(galleryTemplateList[i].find('|')+1));
  }

  for (int i = GalleryTemplateCombo->count() -1; i >=0; i--)
  {
    GalleryTemplateCombo->setCurrentItem(i);
    if (GalleryTemplateCombo->currentText() == KalleryGlobals::ref()->options.galleryTemplate)
    {
      break;
    }
  }

  QStringList encodings(KGlobal::charsets()->availableEncodingNames());
  int pos = 0;
  for (uint i=0; i < encodings.count(); i++)
  {
    EncodingCombo->insertItem(encodings[i]);
    if (encodings[i] == KalleryGlobals::ref()->options.encoding)
      pos = i;
  }
  EncodingCombo->setCurrentItem(pos);
  PageTitleEdit->setText(KalleryGlobals::ref()->options.galleryTitle);
  ColumnNumSpinBox->setValue(KalleryGlobals::ref()->options.columnNum);
  TableColorFrame->setBackgroundColor(KalleryGlobals::ref()->options.tableColor);
  BackColorFrame->setBackgroundColor(KalleryGlobals::ref()->options.backColor);
  TextColorFrame->setBackgroundColor(KalleryGlobals::ref()->options.textColor);
  VisitedColorFrame->setBackgroundColor(KalleryGlobals::ref()->options.visitedColor);

  if (KalleryGlobals::ref()->options.galleryCSSFile.isEmpty())
  {
    UseGalleryCSS->setChecked(false);
  }
  else
  {
    UseGalleryCSS->setChecked(true);
    OwnGalleryCSSName->setText(KalleryGlobals::ref()->options.galleryCSSFile);
  }

  BeforeHtmlEdit->setText(KalleryGlobals::ref()->options.beforeHtmlFile);
  AfterHtmlEdit->setText(KalleryGlobals::ref()->options.afterHtmlFile);
}

//Load the list of avaliable countries and put them into a combo box
//This code is based on kdebase/kcontrol/locale/locale.cpp.
void HtmlOptionsPage::loadCountryList(QComboBox *combo)
{
  QString sub = QString::fromLatin1("l10n/");
  // clear the list
  combo->clear();
  // add all languages to the list
  QStringList countrylist = KGlobal::dirs()->findAllResources("locale",
                               sub + QString::fromLatin1("*/entry.desktop"));
  countrylist.sort();

  for(QStringList::ConstIterator it=++countrylist.begin();it!=countrylist.end();++it)
  {
    KSimpleConfig entry(*it);
    entry.setGroup(QString::fromLatin1("KCM Locale"));
    QString name = entry.readEntry(QString::fromLatin1("Name"),
                       KGlobal::locale()->translate("without name"));
    QString tag = *it;
    int index = tag.findRev('/');
    tag.truncate(index);
    index = tag.findRev('/');
    tag = tag.mid(index+1);
    combo->insertItem(name+" ("+tag+")");
  }
}


/** Load list of the avaliable filters. */
void HtmlOptionsPage::loadTemplates()
{
  QFile tmpFile;
  QString tmpString;

  galleryTemplateList = KGlobal::dirs()-> findAllResources("data","kallery/templates/gallery/*.template", false, true);

  for (uint i = 0; i < galleryTemplateList.count(); i++)
  {
    tmpFile.setName(galleryTemplateList[i]);
    tmpFile.open(IO_ReadOnly);
    tmpFile.readLine(tmpString,200);
    tmpFile.readLine(tmpString,200);
    tmpString.replace(QRegExp("[<>!\n-]"),"");
    galleryTemplateList[i] = galleryTemplateList[i]+"|"+i18n(tmpString);
    defaultColumnsList.append(-1);
    while (!tmpFile.atEnd())
    {
      tmpFile.readLine(tmpString, 200);
      if (tmpString.contains("COLUMNS="))
      {
        tmpString.remove("COLUMNS=");
        defaultColumnsList[i] = tmpString.toInt();
        break;
      }
    }
    tmpFile.close();
  }
}

void HtmlOptionsPage::slotTemplateChanged(int index)
{
  if (defaultColumnsList[index] != -1)
    ColumnNumSpinBox->setValue(defaultColumnsList[index]);
}

#include "htmloptionspage.moc"
