/****************************************************************************
** 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://sf.net/projects/dooble
**   http://dooble.sf.net
****************************************************************************/

#include <QDir>
#include <QBuffer>
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QFileIconProvider>

#include "dmisc.h"
#include "dooble.h"

QNetworkProxy dmisc::proxyByUrl(const QUrl &url)
{
  QNetworkProxy proxy;

  proxy.setType(QNetworkProxy::NoProxy);

  if(url.scheme().toLower() == "ftp")
    if(dooble::s_settings.value("settingsWindow/ftpBrowsingProxyEnabled",
				false).toBool())
      {
	proxy.setHostName(dooble::s_settings.value
			  ("settingsWindow/ftpBrowsingProxyHost",
			   "").toString().trimmed());
	proxy.setPort
	  (static_cast<quint16> (dooble::s_settings.value
				 ("settingsWindow/ftpBrowsingProxyPort",
				  21).toInt()));
      }

  if(url.scheme().toLower() == "http" ||
     url.scheme().toLower() == "https")
    if(dooble::s_settings.value("settingsWindow/proxyEnabled",
				false).toBool())
      {
	QString str("");

	str = dooble::s_settings.value("settingsWindow/proxyType",
				       "Socks5").toString().trimmed().
	  toLower();

	if(str == "socks5")
	  proxy.setType(QNetworkProxy::Socks5Proxy);
	else if(str == "http")
	  proxy.setType(QNetworkProxy::HttpProxy);
	else
	  proxy.setType(QNetworkProxy::Socks5Proxy);

	proxy.setHostName(dooble::s_settings.value("settingsWindow/proxyHost",
						   "").toString().trimmed());
	proxy.setPort
	  (static_cast<quint16> (dooble::s_settings.value
				 ("settingsWindow/proxyPort",
				  1080).toInt()));
	proxy.setUser(dooble::s_settings.value("settingsWindow/proxyUser",
					       "").toString().trimmed());
	proxy.setPassword(dooble::s_settings.value
			  ("settingsWindow/proxyPassword",
			   "").toString().trimmed());
      }

  if(url.host().trimmed().toLower().endsWith(".i2p") &&
     dooble::s_settings.value("settingsWindow/i2pProxyEnabled",
			      true).toBool())
    {
      QString str("");

      str = dooble::s_settings.value("settingsWindow/i2pProxyType",
				     "Http").toString().trimmed().
	toLower();

      if(str == "socks5")
	proxy.setType(QNetworkProxy::Socks5Proxy);
      else if(str == "http")
	proxy.setType(QNetworkProxy::HttpProxy);
      else
	proxy.setType(QNetworkProxy::HttpProxy);

      proxy.setHostName(dooble::s_settings.value
			("settingsWindow/i2pProxyHost",
			 "127.0.0.1").toString().trimmed());
      proxy.setPort
	(static_cast<quint16> (dooble::s_settings.value
			       ("settingsWindow/i2pProxyPort",
				4444).toInt()));
    }

  return proxy;
}

QNetworkProxy dmisc::proxyByFunctionAndUrl
(const DoobleDownloadType::DoobleDownloadTypeEnum functionType,
 const QUrl &url)
{
  QNetworkProxy proxy;

  proxy.setType(QNetworkProxy::NoProxy);

  switch(functionType)
    {
    case DoobleDownloadType::Ftp:
      {
	if(dooble::s_settings.value("settingsWindow/ftpProxyEnabled",
				    false).toBool())
	  {
	    proxy.setHostName(dooble::s_settings.value
			      ("settingsWindow/ftpProxyHost",
			       "").toString().trimmed());
	    proxy.setPort
	      (static_cast<quint16> (dooble::s_settings.value
				     ("settingsWindow/ftpProxyPort",
				      21).toInt()));
	  }

	break;
      }
    case DoobleDownloadType::Http:
      {
	if(dooble::s_settings.value("settingsWindow/httpProxyEnabled",
				    false).toBool())
	  {
	    QString str("");

	    str = dooble::s_settings.value("settingsWindow/httpProxyType",
					   "Socks5").toString().trimmed().
	      toLower();

	    if(str == "socks5")
	      proxy.setType(QNetworkProxy::Socks5Proxy);
	    else if(str == "http")
	      proxy.setType(QNetworkProxy::HttpProxy);
	    else
	      proxy.setType(QNetworkProxy::Socks5Proxy);

	    proxy.setHostName(dooble::s_settings.value
			      ("settingsWindow/httpProxyHost",
			       "").toString().trimmed());
	    proxy.setPort
	      (static_cast<quint16> (dooble::s_settings.value
				     ("settingsWindow/httpProxyPort",
				      1080).toInt()));
	    proxy.setUser(dooble::s_settings.value
			  ("settingsWindow/httpProxyUser",
			   "").toString().trimmed());
	    proxy.setPassword
	      (dooble::s_settings.value("settingsWindow/httpProxyPassword",
					"").toString().trimmed());
	  }

	break;
      }
    default:
      break;
    }

  /*
  ** Override!
  */

  if(url.host().trimmed().toLower().endsWith(".i2p") &&
     dooble::s_settings.value("settingsWindow/di2pProxyEnabled",
			      true).toBool())
    {
      QString str("");

      str = dooble::s_settings.value("settingsWindow/di2pProxyType",
				     "Http").toString().trimmed().
	toLower();

      if(str == "socks5")
	proxy.setType(QNetworkProxy::Socks5Proxy);
      else if(str == "http")
	proxy.setType(QNetworkProxy::HttpProxy);
      else
	proxy.setType(QNetworkProxy::HttpProxy);

      proxy.setHostName(dooble::s_settings.value
			("settingsWindow/di2pProxyHost",
			 "127.0.0.1").toString().trimmed());
      proxy.setPort
	(static_cast<quint16> (dooble::s_settings.value
			       ("settingsWindow/di2pProxyPort",
				4444).toInt()));
    }

  return proxy;
}

QIcon dmisc::iconForUrl(const QUrl &url)
{
  QFileIconProvider iconProvider;

  if(url.scheme().toLower() == "http" ||
     url.scheme().toLower() == "https")
    {
      QIcon icon;

      {
	QFileInfo fileInfo(QDir::homePath() + QDir::separator() +
			   ".dooble" + QDir::separator() + "history.db");
	QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE",
						    "history_dmisc");

	db.setDatabaseName(fileInfo.filePath());

	if(db.open())
	  {
	    QSqlQuery query(db);

	    query.exec
	      (QString("SELECT icon FROM history WHERE url = "
		       "'%1' OR host ='%2'").
	       arg(url.toString(QUrl::StripTrailingSlash)).
	       arg(url.host()));

	    if(query.next())
	      {
		if(!query.isNull(0))
		  {
		    QBuffer buffer;
		    QByteArray bytes
		      (QByteArray::fromBase64(query.value(0).toByteArray()));

		    buffer.setBuffer(&bytes);
		    buffer.open(QIODevice::ReadOnly);

		    QDataStream in(&buffer);

		    in >> icon;
		    buffer.close();
		  }
	      }
	  }

	db.close();
      }

      QSqlDatabase::removeDatabase("history_dmisc");

      if(!icon.isNull())
	return icon;
    }
  else if(url.scheme().toLower() == "ftp")
    return iconProvider.icon(QFileIconProvider::Network);
  else if(url.scheme().toLower() == "file")
    {
      QFileInfo fileInfo(url.toLocalFile());

      if(url.toLocalFile().isEmpty())
	return iconProvider.icon(QFileIconProvider::Folder);
      else if(fileInfo.isFile())
	return iconProvider.icon(QFileIconProvider::File);
      else if(fileInfo.isDir())
	return iconProvider.icon(QFileIconProvider::Folder);
    }

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

  return QIcon(settings.value("mainWindow/emptyIcon").toString());
}
