/***************************************************************************
                          kbiblistview.cpp  -  description
                             -------------------
    begin                : Mon May 26 2003
    copyright            : (C) 2003 by Thach Nguyen
    email                : thach.nguyen@rmit.edu.au
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "kbiblistview.h"
#include <klocale.h>
#include <kglobal.h>
#include <qpixmap.h>
#include <qapplication.h>
#include <qclipboard.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kprocess.h>
#include <krun.h>
#include <ktempfile.h>
#include <kio/netaccess.h>

#include <qdragobject.h>

#include <qfileinfo.h>
#include <qfile.h>
#include "bibentrytable.h"
#include "bibentry.h"


#include "kbibeditentrydlg.h"
#include "kbibinsertfiledlg.h"
#include "kbib.h"
#include "kbibdoc.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


QPtrList<KBibListViewItem> *KBibListView::list_view = 0L;

KBibListView::KBibListView(QWidget* parent, const char *name): KListView(parent, name)
{


    if(!list_view)
    {
        list_view = new QPtrList<KBibListViewItem>();
    }

    list_view->setAutoDelete(true);

    //  addColumn( tr2i18n( "No." ) );
    //addColumn( tr2i18n( "Author" ), 200 );
    //addColumn( tr2i18n( "Key" ) );
    //addColumn( tr2i18n( "Year" ) );
    //addColumn( tr2i18n( "Title" ) );

    updateColumn();

    //  setAllColumnShowFocus(true);
    setShowSortIndicator(true);
    setSelectionMode(QListView::Extended);
    setAllColumnsShowFocus(TRUE);


    setItemMargin(2);

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



    dropMenu = new KPopupMenu(this);
    connect(this,SIGNAL(clicked(QListViewItem *)), this, SLOT(itemSelected(QListViewItem *)));

    connect(this,SIGNAL(doubleClicked(QListViewItem *)), this, SLOT(itemDoubleClicked(QListViewItem *)));
    connect(this, SIGNAL(returnPressed ( QListViewItem *) ), this, SLOT(itemDoubleClicked(QListViewItem *)));

    connect(this, SIGNAL(selectionChanged ()), this, SLOT(slotSelectionChanged()));
    connect(this, SIGNAL(dropped (QDropEvent *, QListViewItem *)), this, SLOT(slotDropped(QDropEvent* )));



    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 Selected References"), this, SLOT(slotEditEntry() ), 0, editID );

    QPixmap remove
        = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("edit_remove"), KIcon::Small);
    m_itemMenu -> insertItem(remove
                             , i18n("Delete Selected References"), 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 Keys of Selected References"), this, SLOT(slotLockKey()), 0, lockID)
    ;
    QPixmap unlock = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("unlock"), KIcon::Small);
    m_itemMenu -> insertItem(unlock, i18n("Unlock Keys of Selected References"), this, SLOT(slotUnlockKey()), 0, unlockID);


    m_itemMenu->insertSeparator();
    m_itemMenu -> insertItem(i18n("Cite Selected References"), 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);

    m_itemMenu -> setItemEnabled (editID, false);
    m_itemMenu -> setItemEnabled (deleteID, false);
    m_itemMenu -> setItemEnabled (cutID, false);
    m_itemMenu -> setItemEnabled (copyID, false);
    m_itemMenu -> setItemEnabled (lockID, false);
    m_itemMenu -> setItemEnabled (unlockID, false);
    m_itemMenu -> setItemEnabled (citeID, false);
    m_itemMenu -> setItemEnabled (urlID, false);
    m_itemMenu -> setItemEnabled (fileID, false);

    dropMenu -> insertItem(copy, i18n("Copy"), this, SLOT(slotDropCopy()));
    dropMenu->insertSeparator();
    QPixmap cancel = KGlobal::iconLoader()->loadIcon(QString::fromLatin1("cancel"), KIcon::Small);
    dropMenu -> insertItem(cancel, i18n("Cancel"), this, SLOT(slotDropCancel()));

    setAcceptDrops(TRUE);
    setDropVisualizer(true);
    setDragEnabled(true);
    setSorting(8);
}
KBibListView::~KBibListView()
{
    delete list_view;
    delete m_itemMenu;
}

void KBibListView::updateColumn()
{
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();

    int addedColumns=0;

    QStringList::iterator it;
    QValueList<int>::iterator s_it;


    s_it = ((win->kbibConfigState).displayFieldsSize).begin();


    for (it =  ((win->kbibConfigState).displayFields).begin(); it != ((win->kbibConfigState).displayFields).end(); ++it)
    {
        addColumn(*it, *s_it);
        s_it++;
        addedColumns++;

    }
    int i;
    int totalColumns = columns();
    for (i = 0; i < (totalColumns - addedColumns); i++)
        removeColumn(i);

    i = 0;
    char fn[256];
    s_it = ((win->kbibConfigState).displayFieldsSize).begin();
    for (it =  ((win->kbibConfigState).displayFields).begin(); it != ((win->kbibConfigState).displayFields).end(); ++it)
    {
        strcpy(fn, (*it).ascii());
        fn[0] = toupper(fn[0]);
        setColumnText(i, fn);
        setColumnWidth(i, *s_it );
        s_it++;
        i++;

    }
    totalColumns = columns();
    //I don't understand why I have to do this!!!!!!!

    for (int j = i; j <  totalColumns; j ++)
        removeColumn(j);


}

void KBibListView::updateListView(BibentryTable * list)
{
    list_view->clear();

    int list_size = list->size();


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

    for (int i = 0; i< list_size; i++)
    {
        //for (int i = list_size-1; i>=0; i--) {
        BibEntry *entry = list->get_entry(i);
		KBibListViewItem * item = new KBibListViewItem(this, win->getDocument(), entry, (win->kbibConfigState).displayFields, (win->kbibConfigState).authorDisplaySetting );
        list_view->append(item);

    }
    emit selectionChanged();
    //  setColumnWidth(0,200);
}


void KBibListView::updateCurrentListView(void)
{

    unsigned int list_size = this->getListSize();

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

    for (unsigned int i = 0; i< list_size; i++)
    {
        KBibListViewItem *item = list_view->at(i);
		item->updateItemContent(win->getDocument(), (win->kbibConfigState).displayFields, (win->kbibConfigState).authorDisplaySetting);


    }
    p_preview->updatePreview();

}




void KBibListView::slotRMB(QListViewItem* item_, const QPoint& point_, int)
{
    //  if(item_ && m_itemMenu->count() > 0) {
    //    setSelected(item_, true);
    itemSelected(item_);
    m_itemMenu->popup(point_);
    //  }
}

QString KBibListView::getSelectedText()
{
    QString st = QString();
    unsigned int list_size = this->getListSize();

    for (unsigned int i = 0; i< list_size; i++)
    {
        KBibListViewItem *item = list_view->at(i);
        if (this->isSelected(item))
        {
            BibEntry *e =  item->getBibEntry();
            st=st+"@"+e->getEntryType()+"{"+e->getKey();
            for (int j=0; j < e-> getNoFields(); j++)
            {
                if (e->getField(j)[0] >= ' ')
                {
                    st=st+",\n\t"+e->getFieldName(j)+"={"+e->getField(j)+"}";

                }

            }
            st=st+",\n}\n";
        }
    }
    return st;

}

void KBibListView::slotCopy()
{

    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotEditCopy();

}


void KBibListView::slotPaste()
{
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();

    win->slotEditPaste();
    //slotSelectionChanged();
}


void KBibListView::slotCut()
{

    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotEditCut();
}





void KBibListView::slotHandleDelete()
{
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotDeleteEntry();
    slotSelectionChanged();
    //p_preview->clear();




}

//void KBibListView::addPreview(QTextView *preview){
//  p_preview = preview;
//}

void KBibListView::addPreview(KBibPreview *preview)
{
    p_preview = preview;
}

/** No descriptions */
void KBibListView::itemSelected(QListViewItem *item_)
{
    if(!item_)
        return;

    //  if(!item_->isSelected());
    //    return;

    KBibListViewItem *item = dynamic_cast<KBibListViewItem*>(item_);



    //  item->setSelected(TRUE);
    item->repaint();
    BibEntry *entry = item->getBibEntry();
    p_preview->setBibEntry(entry);
    p_preview->updatePreview();
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->setCurrentSelectedView(2);

}

void KBibListView::itemDoubleClicked(QListViewItem *item_)
{
    if(!item_)
        return;

    KBibListViewItem *item = dynamic_cast<KBibListViewItem*>(item_);

    BibEntry *entry = item->getBibEntry();

    //  BibEntry *new_entry;

    int index = entry->getIndex();

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

    if (win->editEntry(index))
        updateCurrentListView();




}



/** No descriptions */
void KBibListView::slotNewItem()
{

    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotNewEntry();

}
/** No descriptions */
BibEntry * KBibListView::getItemBibEntry(unsigned int index)
{
    KBibListViewItem *item;
    if ((index >= list_view->count()))
    {
        return 0;
    }
    else
    {
        item = list_view->at(index);
        return item->getBibEntry();
    }

}
/** No descriptions */
unsigned int KBibListView::getListSize(void)
{
    return list_view->count();
}

/*
QString KBibListView::citeSelected()
{
    QString st = QString();
    unsigned int list_size = this->getListSize();
    bool first = true;
 
    for (unsigned int i = 0; i< list_size; i++)
    {
        KBibListViewItem *item = list_view->at(i);
        if (this->isSelected(item))
        {
            BibEntry *entry =  item->getBibEntry();
            if(!first)
            {
                st.append(",");
            }
            st.append(entry->getKey());
            first = false;
        }
    }
 
    if (!st.isNull())
    {
        //st.append("}");
 
        return st;
    }
    else
        return 0;
 
}
*/

void KBibListView::clearListView()
{
    list_view->clear();
    emit selectionChanged();
}


void KBibListView::slotCiteEntry()
{
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotCiteEntry();

}


/** No descriptions */
void KBibListView::slotViewURL()
{
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotViewURL();

}


void KBibListView::slotViewFile()
{
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotViewFile();

}


/** No descriptions */
void KBibListView::slotEditEntry()
{
    unsigned int list_size = this->getListSize();
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    bool change = false;
    for (unsigned int i = 0; i< list_size; i++)
    {
        KBibListViewItem *item = list_view->at(i);
        if (this->isSelected(item))
        {
            BibEntry *entry = item->getBibEntry();
            int index = entry->getIndex();
            if (win->editEntry(index))
                change = true;


        }
    }
    if (change)
        updateCurrentListView();

}

void KBibListView::highlightItem(unsigned int index)
{
    KBibListViewItem *item;
    if ((index >= list_view->count()))
    {
        return;
    }
    else
    {
        //clearSelection();
        item = list_view->at(index);
        setSelected(item,true);
        itemSelected(item);
        ensureItemVisible(item);
    }
}


bool KBibListView::acceptDrag (QDropEvent* event) const
{

    ///event->accept(QTextDrag::canDecode(event));
    if (QTextDrag::canDecode(event))
        return TRUE;
    else
        return FALSE;

}


void KBibListView::slotDropped(QDropEvent* event)
{

    //QString text;

    if (QTextDrag::decode(event, droppedText) )
    {
        // 		cerr << "\nDrop text : " << droppedText.ascii();
        dropMenu->popup(mapToGlobal( contentsToViewport(event->pos()))+QPoint(0,10), 0);

    }
}

void KBibListView::slotDropCopy()
{
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    KBibDoc *doc = win->getDocument();

    KURL url(droppedText.stripWhiteSpace());

    if (url.isValid())
    {

        QString fn = (url.path()).stripWhiteSpace(); //+url.fileName();
        cerr << "\nURL : " << (url.url()).ascii();
        cerr << "\nFile name : " << fn.ascii();
        //Get extention
        QString extension = (((url.fileName()).section( '.', -1 )).stripWhiteSpace()).lower();
        // 		cerr << "\nExtension : " << extension.ascii();
        int numInserted=0;
        int fileType = 0;

        if(extension.compare("bib") == 0)
        {
            // 			cerr << "\nBib file";
            //numInserted = win->insertFile(url, 0, TRUE);
			numInserted = win->insertFile(droppedText.stripWhiteSpace(), 0, TRUE);
            if (numInserted == 0)
                //win->insertFile(url, 1, TRUE);
				numInserted = win->insertFile(droppedText.stripWhiteSpace(), 1, TRUE);
        }
        else if(extension.compare("end") == 0)
        {
            // 			cerr << "\nEnd file";
            //numInserted = win->insertFile(url, 2, TRUE);
			numInserted = win->insertFile(droppedText.stripWhiteSpace(), 2, TRUE);
        }
        else if(extension.compare("ris") == 0)
        {
            // 			cerr << "\nRis file";
            //numInserted = win->insertFile(url, 3, TRUE);
			numInserted = win->insertFile(droppedText.stripWhiteSpace(), 3, TRUE);
        }
        else if(extension.compare("isi") == 0)
        {
            // 			cerr << "\nIsi file";
            //numInserted = win->insertFile(url, 4, TRUE);
			numInserted = win->insertFile(droppedText.stripWhiteSpace(), 4, TRUE);
        }
        else
        {
            //unknown file type, just try
            // 			cerr << "\nGuess file";
            while(numInserted == 0&& fileType < 4)
            {
                //numInserted = win->insertFile(url, fileType, TRUE);
				numInserted = win->insertFile(droppedText.stripWhiteSpace(), fileType, TRUE);
                fileType++;
            }

        }
    }
    else
        doc->paste(droppedText);
}

void KBibListView::slotDropCancel()
{
    dropMenu->hide();
}

void KBibListView::startDrag()
{
    QString st = getSelectedText();
    QDragObject *d = new QTextDrag( st, this );
    d->dragCopy();


}



void KBibListView::saveSelected(KURL url)
{
    if (selectedItems().isEmpty())
    {
        KMessageBox::information(this, i18n("No reference was selected") );
        return;
    }
    unsigned int list_size = this->getListSize();

    QString fileName;
    KTempFile tmpfile;
    tmpfile.setAutoDelete(TRUE);
    if(url.isLocalFile())
    {
        fileName = url.path();
    }
    else
    {
        fileName = tmpfile.name();
    }

    FILE *outf = fopen(fileName.ascii(), "w");
    if (!outf)
    {
        KMessageBox::error(this, i18n("Could not open file for saving") );
        return;
    }

    fprintf(outf, "#Created by Kbib version %s\n", VERSION);
    time_t curr = time(0);
    fprintf(outf, "#Last modified: %s\n\n", ctime(&curr) );

    for (unsigned int i = 0; i< list_size; i++)
    {
        KBibListViewItem *item = list_view->at(i);
        if (this->isSelected(item))
        {
            BibEntry *entry = item->getBibEntry();
            print_entry(outf, entry);
        }
    }

    fclose(outf);

    if (!url.isLocalFile())
    {
        KBibApp* parent = (KBibApp*) this->parent();
        bool uploaded = KIO::NetAccess::upload(fileName, url, parent);
        if(!uploaded)
        {
            QString msg(i18n("Kbib is unable to upload the file - %1.").arg(url.url()));
            KMessageBox::error(parent, msg);
        }
    }
}

void KBibListView::slotLockKey()
{
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotLockKeysSelected();
    /*
    unsigned int list_size = this->getListSize();
       bool change = false;
       KBibListViewItem *item;
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
       for (unsigned int i = 0; i< list_size; i++)
       {
           item = list_view->at(i);
           if (this->isSelected(item))
           {
               BibEntry *entry = item->getBibEntry();
               if (strcmp(entry->getField("lockKey"), "Y")!= 0)
               {
                   entry->setField("lockkey", "Y");
                   change = true;
                   item->updateItemContent((win->kbibConfigState).displayFields);
               }


           }
       }
       if (change)
       {
           emit signalListChange();
           p_preview->updatePreview();
       }
    */

}

void KBibListView::slotUnlockKey()
{
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
    win->slotunLockKeysSelected();
    /*unsigned int list_size = this->getListSize();
       bool change = false;
       KBibListViewItem *item;
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
       for (unsigned int i = 0; i< list_size; i++)
       {
           item = list_view->at(i);
           if (this->isSelected(item))
           {
               BibEntry *entry = item->getBibEntry();
               if (strcmp(entry->getField("lockKey"), "Y")== 0)
               {
                   entry->setField("lockkey", "N");
                   change = true;
                   item->updateItemContent((win->kbibConfigState).displayFields);
               }
           }
       }
       if (change)
       {
           emit signalListChange();
           p_preview->updatePreview();
       }
    */
}

void KBibListView::slotSelectionChanged()
{
    if ( selectedItems().isEmpty() )
    {
        m_itemMenu -> setItemEnabled (editID, false);
        m_itemMenu -> setItemEnabled (deleteID, false);
        m_itemMenu -> setItemEnabled (cutID, false);
        m_itemMenu -> setItemEnabled (copyID, false);
        m_itemMenu -> setItemEnabled (lockID, false);
        m_itemMenu -> setItemEnabled (unlockID, false);
        m_itemMenu -> setItemEnabled (citeID, false);
        m_itemMenu -> setItemEnabled (urlID, false);
        m_itemMenu -> setItemEnabled (fileID, false);
    }
    else
    {
        m_itemMenu -> setItemEnabled (editID, true);
        m_itemMenu -> setItemEnabled (deleteID, true);
        m_itemMenu -> setItemEnabled (cutID, true);
        m_itemMenu -> setItemEnabled (copyID, true);
        m_itemMenu -> setItemEnabled (lockID, true);
        m_itemMenu -> setItemEnabled (unlockID, true);
        m_itemMenu -> setItemEnabled (citeID, true);
        m_itemMenu -> setItemEnabled (urlID, true);
        m_itemMenu -> setItemEnabled (fileID, true);

    }
	
	QListViewItem *i = currentItem();
    if ( !i )
        return;

    if ( !i->isSelected() ) {
        return;
    }
	itemSelected(i);


}

vector<int> *KBibListView::getSelected(void)
{


    if (selectedItems().isEmpty())
    {
        return NULL;
    }
    else
    {
        vector<int> *list = new vector<int>;
        unsigned int list_size = this->getListSize();
        for (unsigned int i = 0; i< list_size; i++)
        {
            KBibListViewItem *item = list_view->at(i);
            if (this->isSelected(item))
            {
                BibEntry *entry =  item->getBibEntry();
                list->push_back(entry->getIndex());
            }
        }
        return list;
    }
}

void KBibListView::addNewItem(BibEntry *entry)
{
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();
	KBibListViewItem * item = new KBibListViewItem(this, win->getDocument(), entry, (win->kbibConfigState).displayFields, (win->kbibConfigState).authorDisplaySetting ) ;
    list_view->append(item);
	setCurrentItem(item);
    item->setSelected(TRUE);
	slotSelectionChanged();
}


void KBibListView::deleteEntry(int index)
{
    int list_size = this->getListSize();
    KBibListViewItem *item;
    for (int i = 0; i< list_size; i++)
    {
        item = list_view->at(i);
        BibEntry *entry =  item->getBibEntry();
        if ((entry->getIndex()) == index)
        {
            list_view->remove(i);
            i = list_size;
        }
    }
}

vector<int> *KBibListView::deleteSelected(void)
{
    if (selectedItems().isEmpty())
    {
        return NULL;
    }
    else
    {
        vector<int> *list = new vector<int>;

        int list_size = this->getListSize();
        KBibListViewItem *item;
        for (int i = 0; i< list_size; i++)
        {
            item = list_view->at(i);
            if (this->isSelected(item))
            {
                BibEntry *entry =  item->getBibEntry();
                list->push_back(entry->getIndex());
                list_view->remove(i);
                i--;
                list_size--;


            }

        }
        //clearSelection();
        return list;

    }
}

void KBibListView::viewSelected(void)
{
        unsigned int list_size = this->getListSize();
        KBibListViewItem *item;
        for (unsigned int i = 0; i< list_size; i++)
        {
            item = list_view->at(i);
            if (!(this->isSelected(item)))
            {
                list_view->remove
                (i);
                i--;
                list_size--;
            }

        }


    
}


void KBibListView::hideSelected(void)
{
    if (selectedItems().isEmpty())
    {
        return ;
    }
    else
    {
        unsigned int list_size = this->getListSize();
        KBibListViewItem *item;
        for (unsigned int i = 0; i< list_size; i++)
        {
            item = list_view->at(i);
            if (this->isSelected(item))
            {
                list_view->remove
                (i);
                i--;
                list_size--;
            }

        }


    }
    p_preview->clear();
}


int KBibListView::showDuplicated()
{
    QSplitter* vbox = (QSplitter*) parent();
    QSplitter* mbox = (QSplitter*) vbox->parent();
    KBibApp* win = (KBibApp*) mbox->parent();

    int compareSetting = (win->kbibConfigState).compareRefSetting;

    clearSelection ();
    int numDuplicated=0;
    BibEntry *thisEntry, *otherEntry;
    KBibListViewItem *thisItem, *otherItem;

    bool duplicated = false;
    int listSize = this->getListSize();
    for (int i =0; i < listSize-1; i++)
    {
        thisItem = list_view->at(i);
        thisEntry = thisItem->getBibEntry();
        if (!this->isSelected(thisItem))
        {
            for (int j = i+1; j < listSize; j++)
            {
                duplicated = false;
                otherItem = list_view->at(j);
                if (!this->isSelected(otherItem))
                {
                    otherEntry = otherItem->getBibEntry();

                    if ( compareBibEntry( thisEntry, otherEntry, compareSetting) == 0)
                    {
                        otherItem->setSelected(TRUE);
                        numDuplicated++;
                    }

                }
            }
        }


    }
    if (numDuplicated)
    {
        for (int i =0; i < listSize; i++)
        {
            thisItem = list_view->at(i);
            if (!this->isSelected(thisItem))
            {
                list_view->remove
                (i);
                i--;
                listSize--;
            }
        }

        emit selectionChanged();
    }
    return numDuplicated;
}

void KBibListView::showByRefType(QString refType)
{
    int listSize = this->getListSize();
    BibEntry *thisEntry;
    KBibListViewItem *thisItem;

    for (int i =0; i < listSize; i++)
    {
        thisItem = list_view->at(i);
        thisEntry = thisItem->getBibEntry();
		if (thisEntry->getEntryType() != refType)
		{
            list_view->remove(i);
            i--;
            listSize--;
        }

    }

}

void KBibListView::invertSelection()
{
    int listSize = this->getListSize();
    KBibListViewItem *thisItem;

    for (int i =0; i < listSize; i++)
    {
        thisItem = list_view->at(i);
        if (this->isSelected(thisItem))
            setSelected(thisItem,FALSE);
        else
            setSelected(thisItem,TRUE);
    }

}





