//
// C++ Implementation: kbibgroupview
//
// Description:
//
//
// Author: Thach Nguyen <thach.nguyen@rmit.edu.au>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "kbibgroupview.h"
#include "kbib.h"
#include <klocale.h>
#include <qstringlist.h>
#include <qpixmap.h>
#include <kiconloader.h>


#define editID 1
#define deleteID 2
#define cutID 3
#define copyID 4
#define lockID 6
#define unlockID 7
#define citeID 8
#define urlID 9
#define fileID 10

KBibGroupView::KBibGroupView(QWidget *parent, const char *name, QString key)
        : KListView(parent, name)
{
    m_list = 0;
	groupBy = key;
    this->addColumn(key);
    this->setShowSortIndicator(true);
    m_groupDict.setAutoDelete(true);
    this->setRootIsDecorated(true);

    connect(this, SIGNAL(rightButtonPressed(QListViewItem*, const QPoint&, int)),
            SLOT(slotRMB(QListViewItem*, const QPoint&, int)));

    popupMenu = new KPopupMenu(this);
    QPixmap expand
    = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("2downarrow"), KIcon::Small);

    popupMenu -> insertItem(expand
                            , i18n("Expand all groups"), this, SLOT(slotExpand()));

    QPixmap collape
    = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("2uparrow"), KIcon::Small);

    popupMenu -> insertItem(expand
                            , i18n("Collape all groups"), this, SLOT(slotCollape()));


    m_itemMenu = new KPopupMenu(this);
    QPixmap add
        = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("edit_add"), KIcon::Small);

    m_itemMenu -> insertItem(add
                             , i18n("Add New Reference"), this, SLOT(slotNewItem()));

    m_itemMenu->insertSeparator();
    QPixmap edit = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("edit"), KIcon::Small);
    m_itemMenu->insertItem(edit, i18n("Edit Reference"), this, SLOT(slotEditEntry() ), 0, editID );


    QPixmap remove
        = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("edit_remove"), KIcon::Small);
    m_itemMenu -> insertItem(remove
                             , i18n("Delete Reference"), this, SLOT(slotHandleDelete()), 0, deleteID);



    m_itemMenu->insertSeparator();


    QPixmap cut = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("editcut"), KIcon::Small);
    m_itemMenu -> insertItem(cut, i18n("Cut"), this, SLOT(slotCut()), 0, cutID);


    QPixmap copy = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("editcopy"), KIcon::Small);
    m_itemMenu -> insertItem(KGlobal::iconLoader()->loadIcon(QString::fromLatin1("editcopy"), KIcon::Small), i18n("Copy"), this, SLOT(slotCopy()), 0, copyID);


    QPixmap paste = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("editpaste"), KIcon::Small);
    m_itemMenu -> insertItem(paste, i18n("Paste"), this, SLOT(slotPaste()));

    m_itemMenu->insertSeparator();
    QPixmap lock = KGlobal::iconLoader()
                       ->loadIcon(QString::fromLatin1("lock"), KIcon::Small);
    m_itemMenu -> insertItem(lock, i18n("Lock Reference Key"), this, SLOT(slotLockKey()), 0, lockID)
    ;
    QPixmap unlock = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("unlock"), KIcon::Small);
    m_itemMenu -> insertItem(unlock, i18n("Unlock Reference Key"), this, SLOT(slotUnlockKey()), 0, unlockID);


    m_itemMenu->insertSeparator();
    m_itemMenu -> insertItem(i18n("Cite Reference"), this, SLOT(slotCiteEntry()), 0, citeID);
    m_itemMenu -> insertItem(i18n("View URL or DOI"), this, SLOT(slotViewURL()), 0, urlID);
    m_itemMenu -> insertItem(i18n("View File"), this, SLOT(slotViewFile()), 0, fileID);

    connect(this,SIGNAL(clicked(QListViewItem *)), this, SLOT(slotItemSelect(QListViewItem *)));
	connect(this, SIGNAL(selectionChanged (QListViewItem *)), this, SLOT(slotSelectionChanged(QListViewItem *)));
    connect(this,SIGNAL(doubleClicked(QListViewItem *)), this, SLOT(slotItemDoubleClicked(QListViewItem *)));
    connect(this, SIGNAL(returnPressed ( QListViewItem *) ), this, SLOT(slotItemDoubleClicked(QListViewItem *)));
	
	this->setSorting(0);
}


KBibGroupView::~KBibGroupView()
{
    m_groupDict.clear();
}

void KBibGroupView::createGroupView()
{
	m_groupDict.clear();
    this->setColumnText(0, groupBy);
	
	if (!m_list) return;
	
    for (int i = 0; i < m_list->size(); i++)
    {
        BibEntry *entry = m_list->get_entry(i);
        addEntry(entry);
    }
	this->setSorting(0);

}


void KBibGroupView::addEntry(BibEntry *entry)
{
    QStringList valueList;

    QString st;

    if (groupBy == QString(i18n("Reference type")) )
    {
        st = entry->getEntryType();
        valueList = QStringList::QStringList(st);
    }
    else
    {
		QString st = entry->getField(groupBy.lower());
        st = st.simplifyWhiteSpace();
		RefField *field = BibEntryDefTable::self()->getRefField(groupBy.lower());
		if (field->type == MULTIPLE && !st.isEmpty()){
			valueList = QStringList::split(field->connectingString, st);	
		}
        else
            valueList =  QStringList::QStringList(st);


    }

    for ( QStringList::Iterator it = valueList.begin(); it != valueList.end(); ++it )
    {
        st = (*it).simplifyWhiteSpace();
        if (!st.isEmpty()){
			KBibGroupViewGroup *group = m_groupDict.find(st.lower());
    	    if (group)
        	{
				group->addEntry(entry);
        	}
        	else
        	{
            	KBibGroupViewGroup *m_group = new KBibGroupViewGroup(st, this);
            	m_group->addEntry(entry);
            	m_groupDict.insert(st.lower(), m_group);
        	}
		}
		else{
			KBibGroupViewGroup *group = m_groupDict.find(QString::fromLatin1("<Empty>"));
    	    if (group)
        	{
            	group->addEntry(entry);
        	}
        	else
        	{
            	KBibGroupViewGroup *m_group = new KBibGroupViewGroup(QString::fromLatin1("<Empty>"), this);
            	m_group->addEntry(entry);
            	m_groupDict.insert(QString::fromLatin1("<Empty>"), m_group);
        	}	
			
		}
    }

}




void KBibGroupView::slotItemSelect(QListViewItem *item_)
{
    if(!item_)
        return;
    KBibGroupViewItem *item = dynamic_cast<KBibGroupViewItem*>(item_);

    if (item)
    {

        //  item->setSelected(TRUE);
        item->repaint();
        BibEntry *entry = item->getBibEntry();
        p_preview->setBibEntry(entry);
        p_preview->updatePreview();

        QFrame *grpViewBox = (QFrame*) parent();
        QSplitter* mbox = (QSplitter*) grpViewBox->parent();
        KBibApp* win = (KBibApp*) mbox->parent();
        win->setCurrentSelectedView(1);
    }
}

void KBibGroupView::slotSelectionChanged(QListViewItem *item_){
	if(!item_)
        return;
	if (item_->isSelected())
		slotItemSelect(item_);	
	
}

void KBibGroupView::slotItemDoubleClicked(QListViewItem *item_)
{
    if(!item_)
        return;

    KBibGroupViewGroup *grpitem = dynamic_cast<KBibGroupViewGroup*>(item_);
    if (grpitem)
    {
        if (grpitem->isOpen())
            grpitem->setOpen(false);
        else
            grpitem->setOpen(true);
        return;
    }

    KBibGroupViewItem *item = dynamic_cast<KBibGroupViewItem*>(item_);
    if (!item)
        return;

    BibEntry *entry = item->getBibEntry();

    //  BibEntry *new_entry;

    int index = entry->getIndex();

    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();

    if (win->editEntry(index))
    {
        createGroupView();
        (win->currentListView())->updateCurrentListView();
    }
}

void KBibGroupView::slotRMB(QListViewItem* item_, const QPoint& point_, int)
{
    if(!item_)
        return;
    KBibGroupViewGroup *grpitem = dynamic_cast<KBibGroupViewGroup*>(item_);
    if (grpitem)
    {
        popupMenu->popup(point_);
        return;
    }
    KBibGroupViewItem *item = dynamic_cast<KBibGroupViewItem*>(item_);
    if (!item)
        return;
    slotItemSelect(item_);
    m_itemMenu->popup(point_);
}

void KBibGroupView::slotExpand()
{
    QListViewItem *item = this->firstChild();
    while (item)
    {
        item->setOpen(true);
        item = item->nextSibling();
    }
}

void KBibGroupView::slotCollape()
{
    QListViewItem *item = this->firstChild();
    while (item)
    {
        item->setOpen(false);
        item = item->nextSibling();
    }
}

void KBibGroupView::slotNewItem()
{
    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotNewEntry();
}

void KBibGroupView::slotEditEntry()
{
    QListViewItem *item_ = this->selectedItem();
    if (!item_)
        return;

    KBibGroupViewItem *item = dynamic_cast<KBibGroupViewItem*>(item_);
    if (!item)
        return;
    BibEntry *entry = item->getBibEntry();

    //  BibEntry *new_entry;

    int index = entry->getIndex();

    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();

    if (win->editEntry(index))
    {
        createGroupView();
        (win->currentListView())->updateCurrentListView();
    }

}

void KBibGroupView::slotHandleDelete()
{

    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotDeleteEntry();

}


void KBibGroupView::slotCut()
{
    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotEditCut();

}

void KBibGroupView::slotCopy()
{
    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotEditCopy();

}


void KBibGroupView::slotPaste()
{
    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotEditPaste();
}

void KBibGroupView::slotCiteEntry()
{
    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotCiteEntry();
}

void KBibGroupView::slotLockKey()
{
    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotLockKeysSelected();
}
void KBibGroupView::slotUnlockKey()
{
    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotunLockKeysSelected();
}
void KBibGroupView::slotViewURL()
{
    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotViewURL();
}

void KBibGroupView::slotViewFile()
{
    QFrame *grpViewBox = (QFrame*) parent();
    QSplitter* mbox = (QSplitter*) grpViewBox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotViewFile();
}

#include "kbibgroupview.moc"
