/***************************************************************************
 *   Copyright (C) 2005 by SUZUKI Tasuku                                   *
 *   tasuku@linux-life.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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "kkatreeview.h"
#include "kkagroup.h"
#include "kkaperson.h"

#include <kglobal.h>
#include <qfile.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kdebug.h>
#include <kmainwindow.h>
#include <kaction.h>
#include <kinputdialog.h>

using namespace KKAddressBook;

KKATreeView::KKATreeView( QWidget* parent, const char* name )
	: KListView( parent, name )
{
	addColumn( i18n( "Group" ) );
	setFullWidth( true );
	setRootIsDecorated( true );
	setDefaultRenameAction( Accept );
	setAcceptDrops( true );
	setDragEnabled( true );
	setDropVisualizer( true );
	setItemsMovable( false );

	readData();

	QString str( i18n( "&Group" ) );	// to translate menu item
	KAction* act;
	act = new KAction( i18n( "&New" ), "group_new", 0, this, SLOT( groupNew() ), actionCollection(), "group_new" );
	act->setToolTip( i18n( "Add new group" ) );

	act = new KAction( i18n( "&Rename" ), "group_edit", 0, this, SLOT( groupRename() ), actionCollection(), "group_edit" );
	act->setToolTip( i18n( "Rename current group" ) );

	act = new KAction( i18n( "&Remove" ), "group_del", 0, this, SLOT( groupRemove() ), actionCollection(), "group_del" );
	act->setToolTip( i18n( "Remove current group" ) );
}

KKATreeView::~KKATreeView()
{
	saveData();
}

void KKATreeView::readData()
{
	QString datafile = locateLocal( "data", KGlobal::instance()->instanceName() + "/address.xml" );
	QDomDocument doc( "kkaddress" );
	QFile file( datafile );
	if( file.open( IO_ReadOnly ) )
	{
		if( !doc.setContent( &file ) )
		{
			createData( doc );
		}
		file.close();
	}
	else
	{
		createData( doc );
	}
	for( QDomNode np = doc.documentElement().lastChild(); !np.isNull(); np = np.previousSibling() )
	{
		new KKAGroup( this, np );
	}
}

void KKATreeView::createData( QDomDocument& doc )
{
	doc.appendChild( doc.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"" ) );
		QDomElement root = doc.createElement( "kkaddress" );
		root.setAttribute( "version", "0.1" );

		QDomElement group = doc.createElement( "group" );
		group.setAttribute( "title", i18n("Friends") );
		group.setAttribute( "isopen", "1" );
		group.setAttribute( "isselected", "1" );
			/* ------------------------------------------------------- */
			QDomElement subgroup = doc.createElement( "group" );
			subgroup.setAttribute( "title", i18n("Neighborhood") );
			group.appendChild( subgroup );
			/* ------------------------------------------------------- */
			QDomElement person = doc.createElement( "person" );
			person.setAttribute( "fullname", i18n("Ichiro Suzuki") );
			person.setAttribute( "firstname", i18n("Ichiro" ) );
			person.setAttribute( "lastname", i18n("Suzuki" ) );
			person.setAttribute( "zipcode", i18n("0000000") );
			person.setAttribute( "address", i18n("Seattle") );
			person.setAttribute( "comment", i18n("Good Job!") );
			group.appendChild( person );
			/* ------------------------------------------------------- */
		root.appendChild( group );
	doc.appendChild( root );
}

void KKATreeView::saveData()
{
// 	cache();
	QString datafile = locateLocal( "data", KGlobal::instance()->instanceName() + "/address.xml" );
	QDomDocument doc( "kkaddress" );
	doc.appendChild( doc.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"" ) );
	QDomElement root = doc.createElement( "kkaddress" );
	root.setAttribute( "version", "0.1" );

	QListViewItem* parent = firstChild();
	while( parent )
	{
		root.appendChild( ((KKAGroup*)parent)->toElement( doc ) );
		parent = parent->nextSibling();
	}
	doc.appendChild( root );
	QFile file( datafile );
	if ( !file.open( IO_WriteOnly ) ){
		KMessageBox::sorry( this, i18n("Can not open file") );
		return;
	}
	QTextStream str( &file );
	str << doc;
	file.close();
}

KActionCollection* KKATreeView::actionCollection()
{
	QPtrList< KMainWindow >* list = KMainWindow::memberList;
	return ((KMainWindow*)list->at(0))->actionCollection();
}

void KKATreeView::groupNew()
{
	QString str = KInputDialog::getText( i18n( "New Group" ), i18n( "Input new group name" ), i18n( "New Item" ) );
	if( str.isNull() ) return;
	KKAGroup* group;
	if( selectedItem() )
	{
		group = new KKAGroup( (KListViewItem*)selectedItem() );
		selectedItem()->setOpen( true );
	}
	else
	{
		group = new KKAGroup( this );
	}
	setCurrentItem( group );
	group->setText( 0, str );
}

void KKATreeView::groupRename()
{
	rename( selectedItem(), 0 );
}

void KKATreeView::groupRemove()
{
	delete selectedItem();
}

QPtrList<KKAContactData> KKATreeView::printData()
{
	QPtrList<KKAContactData> data;
	QListViewItem* parent = firstChild();
	while( parent )
	{
		((KKAGroup*)parent)->addPrintData( data );
		parent = parent->nextSibling();
	}
	return data;
}

void KKATreeView::contentsDragEnterEvent( QDragEnterEvent* event )
{
	event->accept( event->format( 0 ) == "application/x-kreetingkard_person" );
}

void KKATreeView::contentsDragMoveEvent( QDragMoveEvent* event )
{
}

void KKATreeView::contentsDropEvent( QDropEvent* event )
{
	QListViewItem* item = itemAt( event->pos() );
	if( !item ) return;
	if( QString( event->format( 0 ) ) == "application/x-kreetingkard_person" )
	{
		QCString cstr( event->encodedData( "application/x-kreetingkard_person" ) );
		KKAPerson* person = (KKAPerson*)cstr.toLong();
		((QListView*)event->source())->takeItem( person );
		KKAGroup* group = (KKAGroup*)item;
		group->addImportData( person->data() );
	}
}
