/***************************************************************************
 *   Copyright (C) 2004 by Alexander Dymo                                  *
 *   cloudtemple@mksat.net                                                 *
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 *   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.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.             *
 ***************************************************************************/
#include "bookmarkview.h"

#include <tqlayout.h>
#include <tqheader.h>
#include <tqpoint.h>

#include <klineedit.h>
#include <kstandarddirs.h>
#include <tdelocale.h>
#include <kdialog.h>
#include <kpushbutton.h>
#include <kurlrequester.h>
#include <tdepopupmenu.h>
#include <tdeparts/part.h>
#include <tdehtml_part.h>
#include <dom/html_document.h>

#include <kdevpartcontroller.h>
#include <kdevdocumentationplugin.h>

#include "documentation_part.h"
#include "documentation_widget.h"
#include "editbookmarkdlg.h"
#include "docutils.h"

DocBookmarkManager::DocBookmarkManager(DocumentationPart */*part*/)
    :KBookmarkManager(locateLocal("data",
    "kdevdocumentation/bookmarks/bookmarks.xml"), false)
{
    setEditorOptions(i18n("Documentation"), false);
}

DocBookmarkOwner::DocBookmarkOwner(DocumentationPart *part)
    :KBookmarkOwner(), m_part(part)
{
}

void DocBookmarkOwner::openBookmarkURL(const TQString &_url)
{
    m_part->partController()->showDocument(KURL(_url));
}

TQString DocBookmarkOwner::currentURL() const
{
    KParts::ReadOnlyPart *activePart = dynamic_cast<KParts::ReadOnlyPart*>(m_part->partController()->activePart());
    if (activePart)
        return activePart->url().url();
    else
        return TQString();
}

TQString DocBookmarkOwner::currentTitle() const
{
    KParts::ReadOnlyPart *activePart = dynamic_cast<KParts::ReadOnlyPart*>(m_part->partController()->activePart());
    if (activePart)
    {
        TDEHTMLPart *htmlPart = dynamic_cast<TDEHTMLPart*>(activePart);
        if (htmlPart)
            return htmlPart->htmlDocument().title().string();
        return activePart->url().prettyURL();
    }
    else
        return TQString();
}

class DocBookmarkItem: public DocumentationItem {
public:
    DocBookmarkItem(Type type, TDEListView *parent, const TQString &name)
        :DocumentationItem(type, parent, name)
    {
    }
    DocBookmarkItem(Type type, TDEListView *parent, DocumentationItem *after, const TQString &name)
        :DocumentationItem(type, parent, after, name)
    {
    }
    DocBookmarkItem(Type type, DocumentationItem *parent, const TQString &name)
        :DocumentationItem(type, parent, name)
    {
    }
    void setBookmark(const KBookmark &bm) { m_bm = bm; }
    KBookmark bookmark() const { return m_bm; }

private:
    KBookmark m_bm;
};



//class BookmarkView

BookmarkView::BookmarkView(DocumentationWidget *parent, const char *name)
    :TQWidget(parent, name), m_widget(parent)
{
    m_bmManager = new DocBookmarkManager(m_widget->part());
    m_bmOwner = new DocBookmarkOwner(m_widget->part());

    TQVBoxLayout *l = new TQVBoxLayout(this, 0, KDialog::spacingHint());
    m_view = new TDEListView(this);
    m_view->addColumn(i18n("Title"));
    m_view->setSorting(-1);
    m_view->header()->hide();
    m_view->setResizeMode(TQListView::AllColumns);
    m_view->setAllColumnsShowFocus( true );
    l->addWidget(m_view);
    TQHBoxLayout *l2 = new TQHBoxLayout(l, KDialog::spacingHint());
    m_addButton = new KPushButton(i18n("Add"), this);
    m_editButton = new KPushButton(i18n("Edit..."), this);
    m_removeButton = new KPushButton(i18n("Remove"), this);
    l2->addWidget(m_addButton);
    l2->addWidget(m_editButton);
    l2->addWidget(m_removeButton);
    l2->addItem(new TQSpacerItem(1, 1, TQSizePolicy::Expanding, TQSizePolicy::Fixed));
    l->addSpacing(2);

    showBookmarks();

    connect(m_view, TQ_SIGNAL(executed(TQListViewItem*, const TQPoint&, int )),
        this, TQ_SLOT(itemExecuted(TQListViewItem*, const TQPoint&, int )));
    connect(m_addButton, TQ_SIGNAL(pressed()), this, TQ_SLOT(addBookmark()));
    connect(m_editButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(editBookmark()));
    connect(m_removeButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(removeBookmark()));

    connect(m_widget->part(), TQ_SIGNAL(bookmarkLocation(const TQString&, const KURL& )),
        this, TQ_SLOT(addBookmark(const TQString&, const KURL& )));
    connect(m_view, TQ_SIGNAL(mouseButtonPressed(int, TQListViewItem*, const TQPoint&, int )),
        this, TQ_SLOT(itemMouseButtonPressed(int, TQListViewItem*, const TQPoint&, int )));
}

BookmarkView::~BookmarkView()
{
    delete m_bmManager;
    delete m_bmOwner;
}

void BookmarkView::showBookmarks()
{
    const KBookmarkGroup &group = m_bmManager->root();
    DocBookmarkItem *item = 0;
    for (KBookmark bm = group.first(); !bm.isNull(); bm = group.next(bm))
    {
        if (item == 0)
            item = new DocBookmarkItem(DocumentationItem::Document, m_view, bm.fullText());
        else
            item = new DocBookmarkItem(DocumentationItem::Document, m_view, item, bm.fullText());
        item->setURL(bm.url());
        item->setBookmark(bm);
    }
}

void BookmarkView::itemExecuted(TQListViewItem *item, const TQPoint &// p
                                , int // col
                                )
{
    DocumentationItem *docItem = dynamic_cast<DocumentationItem*>(item);
    if (!docItem)
        return;
    m_widget->part()->partController()->showDocument(docItem->url());
}

void BookmarkView::removeBookmark()
{
    if (!m_view->currentItem())
        return;
    DocBookmarkItem *item = dynamic_cast<DocBookmarkItem*>(m_view->currentItem());
    m_bmManager->root().deleteBookmark(item->bookmark());
    m_bmManager->save();
    delete item;
}

void BookmarkView::editBookmark()
{
    if (!m_view->currentItem())
        return;
    DocBookmarkItem *item = dynamic_cast<DocBookmarkItem*>(m_view->currentItem());
    if (!item)
        return;

    EditBookmarkDlg dlg(this);
    dlg.setCaption(i18n("Edit Bookmark"));
    dlg.nameEdit->setText(item->bookmark().fullText());
    dlg.locationEdit->setURL(item->bookmark().url().url());
    dlg.nameEdit->setFocus();
    if (dlg.exec())
    {
        item->bookmark().internalElement().namedItem("title").firstChild().toText().setData(dlg.nameEdit->text());
        item->bookmark().internalElement().setAttribute("href", KURL(dlg.locationEdit->url()).url());
        m_bmManager->save();

        item->setText(0, item->bookmark().fullText());
        item->setURL(item->bookmark().url());
    }
}

void BookmarkView::addBookmark()
{
    TQString title = m_bmOwner->currentTitle();
    TQString url = m_bmOwner->currentURL();

    TDEPopupMenu menu;
    bool useMenu = false;
    if (!title.isEmpty() && !url.isEmpty())
    {
        menu.insertItem(i18n("Current Document"), 1);
        menu.insertItem(i18n("Custom..."), 2);
        useMenu = true;
    }
    int mode = 2;
    if (useMenu)
    {
        m_addButton->setDown(true);
        mode = menu.exec(mapToGlobal(TQPoint(m_addButton->x(), m_addButton->y()+m_addButton->height())));
        m_addButton->setDown(false);
    }

    switch (mode)
    {
        case 1:
            addBookmark(title, url);
            break;
        case 2:
            EditBookmarkDlg dlg(this);
            dlg.setCaption(i18n("Add Bookmark"));
/*            dlg.nameEdit->setText(title);
            dlg.locationEdit->setURL(url);*/
            dlg.nameEdit->setFocus();
            if (dlg.exec())
                addBookmark(dlg.nameEdit->text(), KURL(dlg.locationEdit->url()));
            m_addButton->setDown(false);
            break;
    }
}

void BookmarkView::addBookmark(const TQString &title, const KURL &url)
{
    KBookmark bm = m_bmManager->root().addBookmark(m_bmManager, title, url);
    m_bmManager->save();

    DocBookmarkItem *item = 0;
    if (m_view->lastItem())
        item = dynamic_cast<DocBookmarkItem*>(m_view->lastItem());
    if (item == 0)
        item = new DocBookmarkItem(DocumentationItem::Document, m_view, bm.fullText());
    else
        item = new DocBookmarkItem(DocumentationItem::Document, m_view, item, bm.fullText());
    item->setURL(bm.url());
    item->setBookmark(bm);
}

void BookmarkView::itemMouseButtonPressed(int button, TQListViewItem *item, const TQPoint &pos, int // c
                                          )
{
    if ((button != TQt::RightButton) || (!item))
        return;
    DocumentationItem *docItem = dynamic_cast<DocumentationItem*>(item);
    if (!docItem)
        return;

    DocUtils::docItemPopup(m_widget->part(), docItem, pos, false, true);
}

void BookmarkView::focusInEvent(TQFocusEvent */*e*/)
{
    m_view->setFocus();
}

#include "bookmarkview.moc"
