/****************************************************************************
** Dooble - The Secure Internet Web Browser
**
** Copyright (c) 2008, 2009, 2010 Alexis Megas, 
** Gunther van Dooble, and the Dooble Team. 
** All rights reserved.
**
** License: GPL2 only:
** 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; version 2 of the License only.
**
** This program 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 this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
** or see here: http://www.gnu.org/licenses/gpl.html
**
** For the WebKit library, please see: http://webkit.org.
**
** THE CODE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY
** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
** PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
** IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
** ARISING IN ANY WAY OUT OF THE USE OF THIS APPLICATION, EVEN IF ADVISED
** OF THE POSSIBILITY OF SUCH DAMAGE.
**
** Please report all praise, requests, bugs, and problems to the project
** team and administrators: http://sf.net/projects/dooble.
**
** You can find us listed at our project page. New team members are welcome.
** The name of the authors should not be used to endorse or promote products
** derived from Dooble without specific prior written permission.
** If you use this code for other projects, please let us know.
**
** Web sites:
**   http://dooble.net/projects/dooble
**   http://dooble.sf.net
**   http://www.getadooble.com
****************************************************************************/

#include <QDir>
#include <QMap>
#include <QUrl>
#include <QtDebug>
#include <QLocale>
#include <QSettings>
#include <QFileDialog>
#include <QWebSettings>
#include <QDesktopServices>

#include "dsettings.h"

dsettings::dsettings():QDialog()
{
  ui.setupUi(this);

  QSettings settings;
  QSettings cfgSettings(settings.value("iconSet").toString(),
			QSettings::IniFormat);

  setWindowIcon
    (QIcon(cfgSettings.value("settingsWindow/windowIcon").toString()));
  setSizeGripEnabled(true);
  connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton *)),
	  this, SLOT(slotClicked(QAbstractButton *)));
  connect(ui.chooseIconSetPushButton, SIGNAL(clicked(void)),
	  this, SLOT(slotSelectIconCfgFile(void)));
  connect(ui.chooseMyRetrievedFilesPushButton, SIGNAL(clicked(void)),
	  this, SLOT(slotChooseMyRetrievedFilesDirectory(void)));
  ui.doobleSearchLineEdit->setText
    (QUrl::fromLocalFile(QString("%1/Tab/Default/search.html").arg
			 (QDir::currentPath())).toString());
  settings.setValue("settingsWindow/url12",
		    ui.doobleSearchLineEdit->text().trimmed());

  if(!settings.contains("settingsWindow/myRetrievedFiles"))
    {
      QString path = QDesktopServices::storageLocation
	(QDesktopServices::DesktopLocation);

      if(path.isEmpty() || !QFile::exists(path) ||
	 !QFileInfo(path).isReadable())
	path = QDir::homePath();

      settings.setValue("settingsWindow/myRetrievedFiles", path);
    }

  ui.myRetrievedFilesLineEdit->setText
    (settings.value("settingsWindow/myRetrievedFiles").toString());

  for(int i = 6; i <= 72; i++)
    ui.fontSizeComboBox->addItem(QString::number(i));
}

dsettings::~dsettings()
{
}

void dsettings::exec(QWidget *parent)
{
  QSettings settings;

  ui.url01lineEdit->setText
    (settings.value("settingsWindow/url1", "").toString().trimmed());
  ui.url02lineEdit->setText
    (settings.value("settingsWindow/url2", "").toString().trimmed());
  ui.url03lineEdit->setText
    (settings.value("settingsWindow/url3", "").toString().trimmed());
  ui.url04lineEdit->setText
    (settings.value("settingsWindow/url4", "").toString().trimmed());
  ui.url05lineEdit->setText
    (settings.value("settingsWindow/url5", "").toString().trimmed());
  ui.url06lineEdit->setText
    (settings.value("settingsWindow/url6", "").toString().trimmed());
  ui.url07lineEdit->setText
    (settings.value("settingsWindow/url7", "").toString().trimmed());
  ui.url08lineEdit->setText
    (settings.value("settingsWindow/url8", "").toString().trimmed());
  ui.url09lineEdit->setText
    (settings.value("settingsWindow/url9", "").toString().trimmed());
  ui.url10lineEdit->setText
    (settings.value("settingsWindow/url10", "").toString().trimmed());
  ui.url11lineEdit->setText
    (settings.value("settingsWindow/url11", "").toString().trimmed());
  ui.displayDesktopCheckBox->setChecked
    (settings.value("settingsWindow/displayDesktopCheckBox", false).toBool());
  ui.proceedToNewTabCheckBox->setChecked
    (settings.value("settingsWindow/proceedToNewTab", true).toBool());
  ui.openInNewTabsCheckBox->setChecked
    (settings.value("settingsWindow/openInNewTab", true).toBool());
  ui.standardProxyGroupBox->setChecked
    (settings.value("settingsWindow/proxyEnabled", false).toBool());
  ui.ftpProxyGroupBox->setChecked
    (settings.value("settingsWindow/ftpProxyEnabled", false).toBool());
  ui.httpProxyGroupBox->setChecked
    (settings.value("settingsWindow/httpProxyEnabled", false).toBool());
  ui.proxyType->setCurrentIndex
    (ui.proxyType->findText
     (settings.value("settingsWindow/proxyType",
		     "Socks5").toString().trimmed()));
  ui.proxyHostName->setText(settings.value("settingsWindow/proxyHost",
					   "").toString().trimmed());
  ui.proxyPort->setValue(settings.value("settingsWindow/proxyPort",
					1080).toInt());
  ui.proxyUserName->setText(settings.value("settingsWindow/proxyUser",
					   "").toString().trimmed());
  ui.proxyPassword->setText(settings.value("settingsWindow/proxyPassword",
					   "").toString().trimmed());
  ui.i2pProxyGroupBox->setChecked
    (settings.value("settingsWindow/i2pProxyEnabled", true).toBool());
  ui.i2pProxyType->setCurrentIndex
    (ui.i2pProxyType->findText
     (settings.value("settingsWindow/i2pProxyType",
		     "Http").toString().trimmed()));
  ui.i2pProxyHostName->setText(settings.value
			      ("settingsWindow/i2pProxyHost",
			       "127.0.0.1").toString().trimmed());
  ui.i2pProxyPort->setValue(settings.value("settingsWindow/i2pProxyPort",
					  4444).toInt());
  ui.i2pProxyGroupBox_2->setChecked
    (settings.value("settingsWindow/di2pProxyEnabled", true).toBool());
  ui.i2pProxyType_2->setCurrentIndex
    (ui.i2pProxyType_2->findText
     (settings.value("settingsWindow/di2pProxyType",
		     "Http").toString().trimmed()));
  ui.i2pProxyHostName_2->setText(settings.value
				 ("settingsWindow/di2pProxyHost",
				  "127.0.0.1").toString().trimmed());
  ui.i2pProxyPort_2->setValue(settings.value("settingsWindow/di2pProxyPort",
					     4444).toInt());
  ui.ftpProxyType->setCurrentIndex
    (ui.proxyType->findText
     (settings.value("settingsWindow/ftpProxyType",
		     "Socks5").toString().trimmed()));
  ui.ftpProxyHostName->setText
    (settings.value("settingsWindow/ftpProxyHost",
		    "").toString().trimmed());
  ui.ftpProxyPort->setValue(settings.value("settingsWindow/ftpProxyPort",
					   1080).toInt());
  ui.ftpProxyUserName->setText(settings.value("settingsWindow/ftpProxyUser",
					      "").toString().trimmed());
  ui.ftpProxyPassword->setText
    (settings.value("settingsWindow/ftpProxyPassword",
		    "").toString().trimmed());
  ui.httpProxyType->setCurrentIndex
    (ui.proxyType->findText
     (settings.value("settingsWindow/httpProxyType",
		     "Socks5").toString().trimmed()));
  ui.httpProxyHostName->setText
    (settings.value("settingsWindow/httpProxyHost",
		    "").toString().trimmed());
  ui.httpProxyPort->setValue(settings.value("settingsWindow/httpProxyPort",
					    1080).toInt());
  ui.httpProxyUserName->setText(settings.value("settingsWindow/httpProxyUser",
					       "").toString().trimmed());
  ui.httpProxyPassword->setText
    (settings.value("settingsWindow/httpProxyPassword",
		    "").toString().trimmed());

  if(!settings.value("settingsWindow/url12", "").toString().isEmpty())
    ui.doobleSearchLineEdit->setText
      (settings.value("settingsWindow/url12", "").toString().trimmed());

  ui.urlHistoryGroupBox->setChecked
    (settings.value("settingsWindow/saveHistory", true).toBool());

  if(settings.value("settingsWindow/saveHistoryCheckedId", 0).toInt() == 0)
    ui.deleteAllUrls->setChecked(true);
  else
    ui.saveForNext->setChecked(true);

  QStringList allKeys(settings.allKeys());
  QMap<QString, QString> itemsMap;

  for(int i = 0; i < allKeys.size(); i++)
    if(allKeys[i].contains("iconSet"))
      {
	QSettings cfgSettings
	  (settings.value(allKeys[i]).toString(), QSettings::IniFormat);

	cfgSettings.beginGroup("Description");
	itemsMap[cfgSettings.value("Name").toString()] =
	  settings.value(allKeys[i]).toString();
      }

  allKeys.clear();
  ui.iconSetComboBox->clear();

  QSettings cfgSettings
    (settings.value("iconSet").toString(), QSettings::IniFormat);

  cfgSettings.beginGroup("Description");

  for(int i = 0; i < itemsMap.size(); i++)
    {
      ui.iconSetComboBox->addItem(itemsMap.keys()[i],
				  itemsMap.values()[i]);

      if(cfgSettings.value("Name").toString() == itemsMap.keys()[i])
	ui.iconSetComboBox->setCurrentIndex(i);
    }

  itemsMap.clear();
  ui.javaCheckBox->setChecked
    (settings.value("settingsWindow/javaEnabled", false).toBool());
  ui.javascriptGroupBox->setChecked
    (settings.value("settingsWindow/javascriptEnabled", true).toBool());
  ui.jsAllowNewWindowsCheckBox->setChecked
    (settings.value("settingsWindow/javascriptAllowNewWindows",
		    false).toBool());
  ui.languageComboBox->clear();

  QFont font;

  if(font.fromString(settings.value("settingsWindow/globalFont").toString()))
    {
      ui.fontComboBox->setCurrentFont(font);

      QString globalFontSize(QString::number(font.pointSize()));

      if(ui.fontSizeComboBox->findText(globalFontSize) > -1)
	ui.fontSizeComboBox->setCurrentIndex
	  (ui.fontSizeComboBox->findText(globalFontSize));
      else
	ui.fontSizeComboBox->setCurrentIndex(0);
    }
  else
    {
      ui.fontComboBox->setCurrentFont(QApplication::font());
      ui.fontSizeComboBox->setCurrentIndex(0);
    }

  QLocale locale;

  ui.languageComboBox->addItem(locale.languageToString(locale.language()));

  QPoint p(0, 0);

  if(parent)
    {
      p = parent->pos();

      if(parent->width() >= width())
	p.setX(p.x() + parent->width() / 2 - width() / 2);
      else
	p.setX(p.x() - (width() / 2 - parent->width() / 2));

      if(parent->height() >= height())
	p.setY(p.y() + parent->height() / 2 - height() / 2);
      else
	p.setY(p.y() - (height() / 2 - parent->height() / 2));
    }

  move(p);
  QDialog::exec();
}

void dsettings::slotClicked(QAbstractButton *button)
{
  if(ui.buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
    {
      QSettings settings;

      settings.setValue
	("iconSet",
	 ui.iconSetComboBox->itemData(ui.iconSetComboBox->currentIndex()).
	 toString());
      settings.beginGroup("settingsWindow");
      settings.setValue("size", geometry().size());
      settings.setValue("url1",
			ui.url01lineEdit->text().trimmed());
      settings.setValue("url2",
			ui.url02lineEdit->text().trimmed());
      settings.setValue("url3",
			ui.url03lineEdit->text().trimmed());
      settings.setValue("url4",
			ui.url04lineEdit->text().trimmed());
      settings.setValue("url5",
			ui.url05lineEdit->text().trimmed());
      settings.setValue("url6",
			ui.url06lineEdit->text().trimmed());
      settings.setValue("url7",
			ui.url07lineEdit->text().trimmed());
      settings.setValue("url8",
			ui.url08lineEdit->text().trimmed());
      settings.setValue("url9",
			ui.url09lineEdit->text().trimmed());
      settings.setValue("url10",
			ui.url10lineEdit->text().trimmed());
      settings.setValue("url11",
			ui.url11lineEdit->text().trimmed());
      settings.setValue("url12",
			ui.doobleSearchLineEdit->text().trimmed());
      settings.setValue("myRetrievedFiles",
			ui.myRetrievedFilesLineEdit->text().trimmed());
      settings.setValue("javaEnabled",
			ui.javaCheckBox->isChecked());
      settings.setValue("javascriptEnabled",
			ui.javascriptGroupBox->isChecked());
      settings.setValue("javascriptAllowNewWindows",
			ui.jsAllowNewWindowsCheckBox->isChecked());
      settings.setValue("displayDesktopCheckBox",
			ui.displayDesktopCheckBox->isChecked());
      settings.setValue("proceedToNewTab",
			ui.proceedToNewTabCheckBox->isChecked());
      settings.setValue("openInNewTab",
			ui.openInNewTabsCheckBox->isChecked());
      settings.setValue("proxyEnabled",
			ui.standardProxyGroupBox->isChecked());
      settings.setValue("proxyType",
			ui.proxyType->currentText().trimmed());
      settings.setValue("proxyHost",
			ui.proxyHostName->text().trimmed());
      settings.setValue("proxyPort",
			ui.proxyPort->value());
      settings.setValue("proxyUser",
			ui.proxyUserName->text().trimmed());
      settings.setValue("proxyPassword",
			ui.proxyPassword->text().trimmed());
      settings.setValue("i2pProxyEnabled",
			ui.i2pProxyGroupBox->isChecked());
      settings.setValue("i2pProxyType",
			ui.i2pProxyType->currentText().trimmed());
      settings.setValue("i2pProxyHost",
			ui.i2pProxyHostName->text().trimmed());
      settings.setValue("i2pProxyPort",
			ui.i2pProxyPort->value());
      settings.setValue("di2pProxyEnabled",
			ui.i2pProxyGroupBox_2->isChecked());
      settings.setValue("di2pProxyType",
			ui.i2pProxyType_2->currentText().trimmed());
      settings.setValue("di2pProxyHost",
			ui.i2pProxyHostName_2->text().trimmed());
      settings.setValue("di2pProxyPort",
			ui.i2pProxyPort_2->value());
      settings.setValue("ftpProxyEnabled",
			ui.ftpProxyGroupBox->isChecked());
      settings.setValue("ftpProxyType",
			ui.ftpProxyType->currentText().trimmed());
      settings.setValue("ftpProxyHost",
			ui.ftpProxyHostName->text().trimmed());
      settings.setValue("ftpProxyPort",
			ui.ftpProxyPort->value());
      settings.setValue("ftpProxyUser",
			ui.ftpProxyUserName->text().trimmed());
      settings.setValue("ftpProxyPassword",
			ui.ftpProxyPassword->text().trimmed());
      settings.setValue("httpProxyEnabled",
			ui.httpProxyGroupBox->isChecked());
      settings.setValue("httpProxyType",
			ui.httpProxyType->currentText().trimmed());
      settings.setValue("httpProxyHost",
			ui.httpProxyHostName->text().trimmed());
      settings.setValue("httpProxyPort",
			ui.httpProxyPort->value());
      settings.setValue("httpProxyUser",
			ui.httpProxyUserName->text().trimmed());
      settings.setValue("httpProxyPassword",
			ui.httpProxyPassword->text().trimmed());
      settings.setValue("saveHistory",
			ui.urlHistoryGroupBox->isChecked());

      QFont font(ui.fontComboBox->currentFont());

      font.setPointSize(ui.fontSizeComboBox->currentText().toInt());
      settings.setValue("globalFont", font.toString());

      if(ui.deleteAllUrls->isChecked())
	settings.setValue("saveHistoryCheckedId", 0);
      else
	settings.setValue("saveHistoryCheckedId", 1);

      QWebSettings::globalSettings()->setAttribute
	(QWebSettings::JavaEnabled,
	 ui.javaCheckBox->isChecked());
      QWebSettings::globalSettings()->setAttribute
	(QWebSettings::JavascriptEnabled,
	 ui.javascriptGroupBox->isChecked());
      QWebSettings::globalSettings()->setAttribute
	(QWebSettings::JavascriptCanOpenWindows,
	 ui.jsAllowNewWindowsCheckBox->isChecked());

      for(int i = 0; i < ui.iconSetComboBox->count(); i++)
	settings.setValue(QString("iconSet%1").arg(i + 1),
			  ui.iconSetComboBox->itemData(i));

      emit fontChanged(font);
      emit iconsChanged();
    }

  setVisible(false);
}

void dsettings::keyPressEvent(QKeyEvent *event)
{
  if(event && event->key() == Qt::Key_Escape)
    setVisible(false);
}

void dsettings::slotSelectIconCfgFile(void)
{
  QFileDialog fileDialog(this);

  fileDialog.setWindowTitle(tr("Dooble Web Browser: Theme "
			       "Selection"));
  fileDialog.setDirectory(QDir::homePath());
  fileDialog.setFileMode(QFileDialog::ExistingFile);
  fileDialog.setLabelText(QFileDialog::Accept, tr("&Select"));
  fileDialog.setNameFilter(tr("Theme Configuration File (*.cfg)"));

  if(fileDialog.exec() == QDialog::Accepted)
    {
      QStringList list(fileDialog.selectedFiles());

      if(!list.isEmpty())
	{
	  bool itemInserted = false;
	  QSettings cfgSettings(list[0],
				QSettings::IniFormat);

	  cfgSettings.beginGroup("Description");

	  for(int i = 0; i < ui.iconSetComboBox->count(); i++)
	    if(cfgSettings.value("Name").toString() <
	       ui.iconSetComboBox->itemText(i))
	      {
		itemInserted = true;
		ui.iconSetComboBox->insertItem
		  (i, cfgSettings.value("Name").toString(),
		   list[0]);
		ui.iconSetComboBox->setCurrentIndex(i);
		break;
	      }
	    else if(cfgSettings.value("Name").toString() ==
		    ui.iconSetComboBox->itemText(i))
	      {
		itemInserted = true;
		ui.iconSetComboBox->setCurrentIndex(i);
		break;
	      }

	  if(!itemInserted)
	    {
	      ui.iconSetComboBox->addItem
		(cfgSettings.value("Name").toString(),
		 list[0]);
	      ui.iconSetComboBox->setCurrentIndex
		(ui.iconSetComboBox->count() - 1);
	    }

	  list.clear();
	}
    }
}

void dsettings::slotChooseMyRetrievedFilesDirectory(void)
{
  QFileDialog fileDialog(this);

  fileDialog.setWindowTitle
    (tr("Dooble Web Browser: My Retrieved Files Directory Selection"));
  fileDialog.setFileMode(QFileDialog::Directory);
  fileDialog.setDirectory(QDir::homePath());
  fileDialog.setLabelText(QFileDialog::Accept, tr("&Open"));
  fileDialog.setAcceptMode(QFileDialog::AcceptOpen);

  if(fileDialog.exec() == QDialog::Accepted)
    {
      QStringList list(fileDialog.selectedFiles());

      if(!list.isEmpty())
	{
	  ui.myRetrievedFilesLineEdit->setText(list[0]);
	  list.clear();
	}
    }
}
