/****************************************************************************
** 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 <QUrl>
#include <QStyle>
#include <QLocale>
#include <QWebView>
#include <QSettings>
#include <QBoxLayout>
#include <QPushButton>
#include <QResizeEvent>
#include <QAbstractItemView>

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

durlcompleterview::durlcompleterview(void):QTableView()
{
  setMouseTracking(true);
}

void durlcompleterview::wheelEvent(QWheelEvent *event)
{
  QTableView::wheelEvent(event);

  QModelIndex index(indexAt(event->pos()));

  if(index.isValid())
    {
      selectionModel()->blockSignals(true);
      selectRow(index.row());
      selectionModel()->blockSignals(false);
    }
}

void durlcompleterview::mouseMoveEvent(QMouseEvent *event)
{
  QTableView::mouseMoveEvent(event);

  QModelIndex index(indexAt(event->pos()));

  if(index.isValid())
    {
      selectionModel()->blockSignals(true);
      selectRow(index.row());
      selectionModel()->blockSignals(false);

      /*
      ** Call update(), otherwise more than one item may
      ** be selected.
      */

      update();
    }
}

durlcompleter::durlcompleter(QWidget *parent):QCompleter(parent)
{
  m_tableView = new durlcompleterview();
  m_tableView->setMouseTracking(true);
  m_tableView->setSelectionMode(QAbstractItemView::SingleSelection);
  m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
  m_tableView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
  m_tableView->verticalHeader()->setVisible(false);
  m_tableView->horizontalHeader()->setVisible(false);
  m_tableView->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
  setPopup(m_tableView);
  m_tableView->setStyleSheet
    ("QTableView {"
     "background: lightgray; "
     "selection-background-color: darkgray; "
     "}");
}

durlcompleter::~durlcompleter()
{
  while(!m_purgedItems.isEmpty())
    delete m_purgedItems.takeFirst();
}

bool durlcompleter::exists(const QString &text) const
{
  return m_allUrls.contains(text);
}

void durlcompleter::clear(void)
{
  m_model->clear();

  while(!m_purgedItems.isEmpty())
    delete m_purgedItems.takeFirst();
}

void durlcompleter::setModel(QStandardItemModel *model)
{
  m_model = model;
  QCompleter::setModel(m_model);
}

void durlcompleter::saveItemUrl(const QString &url)
{
  m_allUrls.append(url);
}

void durlcompleter::setCompletion
(const QString &completion)
{
  m_model->blockSignals(true);

  while(!m_purgedItems.isEmpty())
    {
      m_model->setRowCount(m_model->rowCount() + 1);
      m_model->setItem(m_model->rowCount() - 1, m_purgedItems.takeFirst());
    }

  QList<QStandardItem *> list;

  if(completion.trimmed().isEmpty())
    {
      for(int i = 0; i < m_model->rowCount(); i++)
	if(m_model->item(i))
	  list.append(m_model->item(i)->clone());
    }
  else
    {
      QList<QStandardItem *> tmplists[4];

      for(int i = 0; i < m_model->rowCount(); i++)
	if(m_model->item(i))
	  {
	    if(m_model->item(i)->text() == completion.trimmed())
	      tmplists[0].append(m_model->item(i)->clone());
	    else if(m_model->item(i)->text().startsWith(completion.trimmed()))
	      tmplists[1].append(m_model->item(i)->clone());
	    else if(m_model->item(i)->text().endsWith(completion.trimmed()))
	      tmplists[2].append(m_model->item(i)->clone());
	    else if(m_model->item(i)->text().contains(completion.trimmed()))
	      tmplists[3].append(m_model->item(i)->clone());
	    else
	      m_purgedItems.append(m_model->item(i)->clone());
	  }

      list << tmplists[0] << tmplists[1] << tmplists[2] << tmplists[3];
      tmplists[0].clear();
      tmplists[1].clear();
      tmplists[2].clear();
      tmplists[3].clear();
    }

  m_model->clear();

  while(list.size() > 1)
    {
      m_model->setRowCount(m_model->rowCount() + 1);
      m_model->setItem(m_model->rowCount() - 1, list.takeFirst());
    }

  /*
  ** Unblock signals on the model and add the last list entry. This little
  ** trick will allow for a smoother update of the table's contents.
  */

  m_model->blockSignals(false);

  while(!list.isEmpty())
    {
      m_model->setRowCount(m_model->rowCount() + 1);
      m_model->setItem(m_model->rowCount() - 1, list.takeFirst());
    }

  if(m_model->rowCount() > 0)
    {
      if(m_model->rowCount() > 10)
	m_tableView->setVerticalScrollBarPolicy
	  (Qt::ScrollBarAlwaysOn);
      else
	m_tableView->setVerticalScrollBarPolicy
	  (Qt::ScrollBarAlwaysOff);

      m_tableView->setFixedHeight
	(qMin(10, m_model->rowCount()) * m_tableView->rowHeight(0));
      complete();
    }
  else
    popup()->setVisible(false);
}

durlwidget::durlwidget(QWidget *parent):QLineEdit(parent)
{
  goToolButton = new QToolButton(this);
  goToolButton->setToolTip(tr("Load URL"));
  goToolButton->setIconSize(QSize(16, 16));
  goToolButton->setCursor(Qt::ArrowCursor);
  goToolButton->setStyleSheet("QToolButton {"
			      "border: none; "
			      "padding-bottom: 0px; "
			      "}");
  bookmarkToolButton = new QToolButton(this);
  bookmarkToolButton->setToolTip(tr("Bookmark URL"));
  bookmarkToolButton->setIconSize(QSize(16, 16));
  bookmarkToolButton->setCursor(Qt::ArrowCursor);
  bookmarkToolButton->setStyleSheet("QToolButton {"
				    "border: none; "
				    "padding-bottom: 0px; "
				    "}");
  pulldownToolButton = new QToolButton(this);
  pulldownToolButton->setIconSize(QSize(16, 16));
  pulldownToolButton->setCursor(Qt::ArrowCursor);
  pulldownToolButton->setStyleSheet("QToolButton {"
				    "border: none; "
				    "padding-bottom: 0px; "
#ifdef Q_WS_MAC
				    "padding-right: 10px; "
#else
				    "padding-right: 15px; "
#endif
				    "}");
  slotSetIcons();
  connect(this, SIGNAL(returnPressed(void)), this,
	  SLOT(slotReturnPressed(void)));
  connect(pulldownToolButton, SIGNAL(clicked(void)), this,
	  SLOT(slotPulldownClicked(void)));
  connect(bookmarkToolButton, SIGNAL(clicked(void)), this,
          SLOT(slotBookmark(void)));

  /*
  ** The menu is for display purposes only.
  */

  pulldownToolButton->setMenu(new QMenu(this));

  int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);

  setStyleSheet
    (QString("QLineEdit {padding-right: %1px; padding-left: %2px; "
	     "selection-background-color: darkgray;}").
     arg(goToolButton->sizeHint().width() + frameWidth + 1).
     arg(pulldownToolButton->sizeHint().width() +
	 bookmarkToolButton->sizeHint().width() +
	 frameWidth + 1));
  setMinimumHeight(sizeHint().height() + 5);
  m_completer = new durlcompleter(this);
  m_completer->setModel(new QStandardItemModel(m_completer));
  m_completer->setModelSorting(QCompleter::UnsortedModel);
  m_completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
  m_completer->setCaseSensitivity(Qt::CaseInsensitive);
  connect(m_completer,
	  SIGNAL(activated(const QString &)),
	  this,
	  SLOT(slotLoadPage(const QString &)));
  setCompleter(m_completer);
}

void durlwidget::addItem(const QString &text)
{
  if(text.isEmpty())
    return;

  if(!m_completer)
    return;

  /*
  ** Prevent duplicates. We can't use the model's findItems()
  ** as the model may contain a subset of the completer's
  ** items due to filtering.
  */

  if(m_completer->exists(text))
    return;

  if(!dooble::s_settings.value("settingsWindow/rememberHistory",
			       false).toBool())
    return;

  QStandardItemModel *model = qobject_cast<QStandardItemModel *>
    (m_completer->model());

  if(model)
    {
      m_completer->saveItemUrl(text);
      model->setRowCount(model->rowCount() + 1);

      QStandardItem *item = new QStandardItem
	(dmisc::iconForUrl(QUrl(text)), text);

      model->setItem(model->rowCount() - 1, item);
    }
}

void durlwidget::addItem(const QString &text, const QIcon &icon)
{
  if(text.isEmpty())
    return;

  if(!m_completer)
    return;

  /*
  ** Prevent duplicates. We can't use the model's findItems()
  ** as the model may contain a subset of the completer's
  ** items due to filtering.
  */

  if(m_completer->exists(text))
    return;

  if(!dooble::s_settings.value("settingsWindow/rememberHistory",
			       false).toBool())
    return;

  QStandardItemModel *model = qobject_cast<QStandardItemModel *>
    (m_completer->model());

  if(model)
    {
      m_completer->saveItemUrl(text);
      model->setRowCount(model->rowCount() + 1);

      QStandardItem *item = 0;

      if(icon.isNull())
	item = new QStandardItem(dmisc::iconForUrl(QUrl(text)), text);
      else
	item = new QStandardItem(icon, text);

      model->setItem(model->rowCount() - 1, item);
    }
}

void durlwidget::setIcon(const QIcon &icon)
{
  if(icon.isNull())
    pulldownToolButton->setIcon(dmisc::iconForUrl(QUrl(text())));
  else
    pulldownToolButton->setIcon(icon);
}

void durlwidget::setText(const QString &text)
{
  QLineEdit::setText(text);
  setCursorPosition(0);
}

void durlwidget::selectAll(void)
{
  setCursorPosition(text().length());
  cursorBackward(true, text().length());
}

void durlwidget::resizeEvent(QResizeEvent *event)
{
  int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
  QSize size1 = goToolButton->sizeHint();
  QSize size2 = pulldownToolButton->sizeHint();
  QSize size3 = bookmarkToolButton->sizeHint();

  goToolButton->move
    (rect().right() - frameWidth - size1.width(),
     (rect().bottom() + 2 - size1.height()) / 2);
  pulldownToolButton->move
    (frameWidth - rect().left() + size3.width() + 1,
     (rect().bottom() + 2 - size2.height()) / 2);
  bookmarkToolButton->move
    (frameWidth - rect().left() + 1,
     (rect().bottom() + 2 - size3.height()) / 2);

  if(selectedText().isEmpty())
    setCursorPosition(0);

  QLineEdit::resizeEvent(event);
}

void durlwidget::setItemIcon(const int index , const QIcon &icon)
{
  if(!m_completer)
    return;

  QStandardItemModel *model = qobject_cast<QStandardItemModel *>
    (m_completer->model());

  if(!model)
    return;

  QStandardItem *item = model->item(index);

  if(item)
    {
      if(icon.isNull())
	item->setIcon(dmisc::iconForUrl(QUrl(item->text())));
      else
	item->setIcon(icon);
    }
}

void durlwidget::slotPulldownClicked(void)
{
  if(!m_completer)
    return;

  m_completer->setCompletion("");

  /*
  ** I'm not sure why I need to do this. It appears
  ** that the activated() signal is lost whenever
  ** m_completer's model has changed.
  */

  disconnect(m_completer,
	     SIGNAL(activated(const QString &)),
	     this,
	     SLOT(slotLoadPage(const QString &)));
  connect(m_completer,
	  SIGNAL(activated(const QString &)),
	  this,
	  SLOT(slotLoadPage(const QString &)));
}

int durlwidget::findText(const QString &text) const
{
  int index = -1;

  if(text.isEmpty())
    return index;

  if(!m_completer)
    return index;

  QStandardItemModel *model = qobject_cast<QStandardItemModel *>
    (m_completer->model());

  if(!model)
    return index;

  QList<QStandardItem *> list(model->findItems(text));

  if(!list.isEmpty())
    index = list.at(0)->row();

  list.clear();
  return index;
}

QToolButton *durlwidget::goButton(void) const
{
  return goToolButton;
}

void durlwidget::slotSetIcons(void)
{
  QSettings settings
    (dooble::s_settings.value("iconSet").toString(), QSettings::IniFormat);

  settings.beginGroup("urlWidget");
  goToolButton->setIcon(QIcon(settings.value("goToolButton").toString()));
  bookmarkToolButton->setIcon
    (QIcon(settings.value("bookmarkToolButton").toString()));

  if(pulldownToolButton->icon().isNull())
    pulldownToolButton->setIcon
      (QIcon(settings.value("emptyIcon").toString()));
}

void durlwidget::slotBookmark(void)
{
}

void durlwidget::copy(void)
{
  QLineEdit::copy();
}

bool durlwidget::event(QEvent *e)
{
  if(e && e->type() == QEvent::KeyPress &&
     static_cast<QKeyEvent *> (e)->key() == Qt::Key_Tab)
    {
      QTableView *table = qobject_cast<QTableView *> (m_completer->popup());

      if(table)
	{
	  int row = 0;

	  if(!table->isVisible())
	    {
	      slotPulldownClicked();
	      table->setCurrentIndex(table->rootIndex());
	    }
	  else if(table->selectionModel()->
		  isRowSelected(table->currentIndex().row(),
				table->rootIndex()))
	    {
	      row = table->currentIndex().row() + 1;

	      if(row >= m_completer->model()->rowCount())
		row = 0;
	    }

	  table->selectRow(row);
	}

      return true;
    }

  return QLineEdit::event(e);
}

void durlwidget::keyPressEvent(QKeyEvent *event)
{
  bool delegateKeyPressEvent = true;

  if(event)
    {
      QKeySequence userKeys(event->modifiers() + event->key());

      if(event->key() == Qt::Key_Up || event->key() == Qt::Key_Down)
	slotPulldownClicked();
      else if(userKeys == QKeySequence(Qt::AltModifier + Qt::Key_Enter) ||
	      userKeys == QKeySequence(Qt::AltModifier + Qt::Key_Return))
	{
	  delegateKeyPressEvent = false;
	  emit openLinkInNewTab(QUrl::fromUserInput(text().trimmed()));
	}
      else if(userKeys == QKeySequence(Qt::ControlModifier +
				       Qt::Key_Enter) ||
	      userKeys == QKeySequence(Qt::ControlModifier +
				       Qt::Key_Return))
	{
	  QUrl url(QUrl::fromUserInput(text().trimmed()));

	  if(!url.host().endsWith(".com"))
	    url.setHost(url.host() + ".com");

	  emit loadPage(url);
	}
      else if(userKeys == QKeySequence(Qt::ShiftModifier + Qt::Key_Enter) ||
	      userKeys == QKeySequence(Qt::ShiftModifier + Qt::Key_Return))
	{
	  QUrl url(QUrl::fromUserInput(text().trimmed()));

	  if(!url.host().endsWith(".net"))
	    url.setHost(url.host() + ".net");

	  emit loadPage(url);
	}
      else if(userKeys ==
	      QKeySequence(Qt::ControlModifier + Qt::ShiftModifier +
			   Qt::Key_Enter) ||
	      userKeys ==
	      QKeySequence(Qt::ControlModifier + Qt::ShiftModifier +
			   Qt::Key_Return))
	{
	  QUrl url(QUrl::fromUserInput(text().trimmed()));

	  if(!url.host().endsWith(".org"))
	    url.setHost(url.host() + ".org");

	  emit loadPage(url);
	}
      else if(userKeys == QKeySequence(Qt::Key_Escape))
	emit resetUrl();
      else if(userKeys == QKeySequence(Qt::ControlModifier +
				       Qt::Key_L))
	{
	  setFocus();
	  selectAll();
	  update();
	}
      else if(event->key() == Qt::Key_Enter ||
	      event->key() == Qt::Key_Return)
	{
	  /*
	  ** Let the parent handle the event.
	  */

	  QLineEdit::keyPressEvent(event);
	  return;
	}
    }

  if(delegateKeyPressEvent)
    QLineEdit::keyPressEvent(event);
  else if(m_completer)
    m_completer->popup()->setVisible(false);

  if(delegateKeyPressEvent &&
     !text().trimmed().isEmpty() &&
     event &&
     event->key() != Qt::Key_Escape &&
     event->modifiers() == Qt::NoModifier &&
     m_completer)
    {
      m_completer->setCompletion(text().trimmed());

      /*
      ** I'm not sure why I need to do this. It appears
      ** that the activated() signal is lost whenever
      ** m_completer's model has changed.
      */

      disconnect(m_completer,
		 SIGNAL(activated(const QString &)),
		 this,
		 SLOT(slotLoadPage(const QString &)));
      connect(m_completer,
	      SIGNAL(activated(const QString &)),
	      this,
	      SLOT(slotLoadPage(const QString &)));
    }
}

void durlwidget::slotLoadPage(const QString &url)
{
#ifdef Q_WS_MAC
  if(m_completer)
    m_completer->popup()->setVisible(false);
#endif
  emit loadPage(QUrl(url));
}

void durlwidget::clearHistory(void)
{
  if(!m_completer)
    return;

  m_completer->clear();
}

void durlwidget::slotReturnPressed(void)
{
  if(m_completer)
    m_completer->popup()->setVisible(false);
}
