//
// C++ Implementation: kbibgroupview
//
// Description:
//
//
// Author: Thach Nguyen <thach.nguyen@rmit.edu.au>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "kbibgroupviewgroup.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

KBibGroupViewGroup::KBibGroupViewGroup(KListView *parent, QString key)
        : KListViewItem(parent)
{
    m_list = 0;
	groupBy = key;
	this->setText(0, groupBy);
	m_groupDict.setAutoDelete(TRUE);
	this->setSelectable ( false );
}


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

void KBibGroupViewGroup::createGroup(BibentryTable *m_list)
{
	m_groupDict.clear();
	
	if (!m_list) return;
	
    for (int i = 0; i < m_list->size(); i++)
    {
        BibEntry *entry = m_list->get_entry(i);
        addEntry(entry);
    }

}


void KBibGroupViewGroup::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()){
			if (groupBy == QString("AUTHOR") || groupBy == QString("EDITOR") ){
				st = reformatAuthor(st);
			} 

			KBibGroupViewItem *group = m_groupDict.find(st.lower());
    	    if (group)
        	{	
				group->addEntry(entry);
        	}
        	else
        	{
            	KBibGroupViewItem *m_group = new KBibGroupViewItem(st, this);
            	m_group->addEntry(entry);
            	m_groupDict.insert(st.lower(), m_group);
				m_group->setPixmap(0, SmallIcon(QString::fromLatin1("folder")));
        	}
		}
/*		else{
			KBibGroupViewItem *group = m_groupDict.find(QString::fromLatin1("<Empty>"));
    	    if (group)
        	{
            	group->addEntry(entry);
        	}
        	else
        	{
            	KBibGroupViewItem *m_group = new KBibGroupViewItem(QString::fromLatin1("<Empty>"), this);
            	m_group->addEntry(entry);
            	m_groupDict.insert(QString::fromLatin1("<Empty>"), m_group);
        	}	
			
		}
*/
    }

}



#include "kbibgroupviewgroup.moc"
