/*
    kopetelistview.cpp - List View providing support for ListView::Items

    Copyright (c) 2004      by Engin AYDOGAN	      <engin@bzzzt.biz>
    Copyright (c) 2004      by Richard Smith          <kde@metafoo.co.uk>

    Kopete    (c) 2004      by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * 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 "kopetelistview.h"
#include "kopetelistviewitem.h"
#include "kopeteuiglobal.h"
#include "kopeteglobal.h"
#include "kopeteprefs.h"

#include <tqapplication.h>
#include <tdeglobal.h>
#include <tdeconfig.h>
#include <kdebug.h>

#include <tqtimer.h>
#include <tqtooltip.h>
#include <tqstyle.h>

#include <utility>
#include <memory>

namespace Kopete {
namespace UI {
namespace ListView {

/*
 Custom TQToolTip for the list view.
 The decision whether or not to show tooltips is taken in
 maybeTip(). See also the TQListView sources from TQt itself.
 Delegates to the list view items.
*/
class ToolTip : public TQToolTip
{
public:
	ToolTip( TQWidget *parent, ListView *lv );
	virtual ~ToolTip();

	void maybeTip( const TQPoint &pos );

private:
	ListView *m_listView;
};

ToolTip::ToolTip( TQWidget *parent, ListView *lv )
 : TQToolTip( parent )
{
	m_listView = lv;
}

ToolTip::~ToolTip()
{
}

void ToolTip::maybeTip( const TQPoint &pos )
{
	if( !parentWidget() || !m_listView )
		return;

	if( Item *item = dynamic_cast<Item*>( m_listView->itemAt( pos ) ) )
	{
		TQRect itemRect = m_listView->itemRect( item );

		uint leftMargin = m_listView->treeStepSize() *
		   ( item->depth() + ( m_listView->rootIsDecorated() ? 1 : 0 ) ) +
		   m_listView->itemMargin();

		uint xAdjust = itemRect.left() + leftMargin;
		uint yAdjust = itemRect.top();
		TQPoint relativePos( pos.x() - xAdjust, pos.y() - yAdjust );

		std::pair<TQString,TQRect> toolTip = item->toolTip( relativePos );
		if ( toolTip.first.isEmpty() )
			return;

		toolTip.second.moveBy( xAdjust, yAdjust );
// 		kdDebug( 14000 ) << k_funcinfo << "Adding tooltip: itemRect: "
// 		                 << toolTip.second << ", tooltip:  " << toolTip.first << endl;
		tip( toolTip.second, toolTip.first );
	}
}

struct ListView::Private
{
	TQTimer sortTimer;
	std::unique_ptr<ToolTip> toolTip;
	//! C-tor
	Private() {}
	Private(Private const &) = delete;
	Private& operator=(Private const &) = delete;
};

ListView::ListView( TQWidget *parent, const char *name )
 : TDEListView( parent, name ), d( new Private )
{
	connect( &d->sortTimer, TQ_SIGNAL( timeout() ), this, TQ_SLOT( slotSort() ) );

	// We have our own tooltips, don't use the default TQListView ones
	setShowToolTips( false );
	d->toolTip.reset( new ToolTip( viewport(), this ) );

	connect( this, TQ_SIGNAL( contextMenu( TDEListView *, TQListViewItem *, const TQPoint & ) ),
	         TQ_SLOT( slotContextMenu( TDEListView *, TQListViewItem *, const TQPoint & ) ) );
	connect( this, TQ_SIGNAL( doubleClicked( TQListViewItem * ) ),
	         TQ_SLOT( slotDoubleClicked( TQListViewItem * ) ) );

	// set up flags for nicer painting
	clearWFlags( WStaticContents );
	setWFlags( WNoAutoErase );

	// clear the appropriate flags from the viewport - qt docs say we have to mask
	// these flags out of the TQListView to make weirdly painted list items work, but
	// that doesn't do the job. masking them out of the viewport does.
//	class MyWidget : public TQWidget { public: using TQWidget::clearWFlags; };
//	static_cast<MyWidget*>( viewport() )->clearWFlags( WStaticContents );
//	static_cast<MyWidget*>( viewport() )->setWFlags( WNoAutoErase );

	// The above causes compiler errors with the (broken) native TRU64 and IRIX compilers.
	// This should make it compile for both platforms and still seems to work.
	// This is, of course, a nasty hack, but it works, so...
	static_cast<ListView*>(viewport())->clearWFlags( WStaticContents );
	static_cast<ListView*>(viewport())->setWFlags( WNoAutoErase );
}

ListView::~ListView()
{
	delete d;
}

void ListView::slotDoubleClicked( TQListViewItem *item )
{
	kdDebug( 14000 ) << k_funcinfo << endl;

	if ( item )
		setOpen( item, !isOpen( item ) );
}

void ListView::slotContextMenu( TDEListView * /*listview*/,
	TQListViewItem *item, const TQPoint &/*point*/ )
{
	if ( item && !item->isSelected() )
	{
		clearSelection();
		item->setSelected( true );
	}
	if ( !item )
		clearSelection();

//	if( Item *myItem = dynamic_cast<Item*>( item ) )
		;// TODO: myItem->contextMenu( point );
}

void ListView::setShowTreeLines( bool bShowAsTree )
{
	if ( bShowAsTree )
	{
		setRootIsDecorated( true );
		setTreeStepSize( 20 );
	}
	else
	{
		setRootIsDecorated( false );
		setTreeStepSize( 0 );
	}
	// TODO: relayout all items. their width may have changed, but they won't know about it.
}

/* This is a small hack ensuring that only F2 triggers inline
 * renaming. Won't win a beauty award, but whoever wrote it thinks
 * relying on the fact that TQListView intercepts and processes the
 * F2 event through this event filter is sorta safe.
 *
 * Also use enter to execute the item since executed is not usually
 * called when enter is pressed.
 */
void ListView::keyPressEvent( TQKeyEvent *e )
{
	TQListViewItem *item = currentItem();
	if ( (e->key() == TQt::Key_F2) && item && item->isVisible() )
		rename( item, 0 );
	else if ( (e->key() == TQt::Key_Enter || e->key() == TQt::Key_Return) && item && item->isVisible() )
	{
		// must provide a point within the item; emitExecute checks for this
		TQPoint p = viewport()->mapToGlobal(itemRect(item).center());
		emitExecute( currentItem(), p, 0 );
	}
	else
		TDEListView::keyPressEvent(e);
}

void ListView::delayedSort()
{
	if ( !d->sortTimer.isActive() )
		d->sortTimer.start( 500, true );
}

} // END namespace ListView
} // END namespace UI
} // END namespace Kopete

#include "kopetelistview.moc"
