/* ====================================================================
 * Copyright 2006-2007,     Martin Hauner
 *                          http://subcommander.tigris.org
 *
 * Subcommander is licensed as described in the file doc/COPYING, which
 * you should have received as part of this distribution.
 * ====================================================================
 */

// sc
#include "config.h"
#include "LogWidget.h"
#include "LogLvi.h"

// qt
#include <QtGui/QMouseEvent>
#include <Qt3Support/Q3Header>



LogWidget::LogWidget( QWidget *parent )
: super( parent ), _lastActiveId(0)
{
  setTreeStepSize(10);
  setRootIsDecorated(true);
  setAllColumnsShowFocus(true);
  setSorting(0,true);
  addColumn( "" ); // activity
  addColumn( "" ); // status
  addColumn( "" ); // message
  addColumn( "" ); // empty
  setResizeMode( Q3ListView::LastColumn );
  setColumnAlignment(1,Qt::AlignHCenter);
  header()->hide();
  viewport()->setMouseTracking(true);

  connect( 
    this, SIGNAL(clicked(Q3ListViewItem*,const QPoint&,int)),
    this, SLOT(clicked(Q3ListViewItem*,const QPoint&,int)) );
}

LogWidget::~LogWidget()
{
}

void LogWidget::clicked( Q3ListViewItem* item, const QPoint& pnt, int c )
{
  if( ! item )
  {
    return;
  }

  QPoint p1 = mapFromGlobal(pnt);
  QPoint p2 = viewport()->mapFromParent(p1);

  LogLvi* lvi = dynamic_cast<LogLvi*>(item);
  if( lvi->isOnCancel(p2.x()) )
  {
    lvi->setCanceled();
  }
}

void LogWidget::contentsMouseMoveEvent( QMouseEvent* e )
{
  LogLvi* lastLvi = findItem(_lastActiveId);
  if( lastLvi )
  {
    lastLvi->setCancelNormal();
    _lastActiveId = 0;
  }

  QPoint p1 = mapFromGlobal(e->globalPos());
  QPoint p2 = viewport()->mapFromParent(p1);

  LogLvi* lvi = dynamic_cast<LogLvi*>(itemAt(p2));
  if( lvi )
  {
    if( lvi->isCancelable() && lvi->isOnCancel(e->x()) )
    {
      lvi->setCancelActive();
      _lastActiveId = lvi->getId();
    }
  }
}

LogLvi* LogWidget::findItem( long id ) const
{
  Q3ListViewItemIterator it((Q3ListView*)this);
  while( it.current() )
  {
    LogLvi* item = (LogLvi*)it.current();
    if( item->getId() == (unsigned long)id )
    {
      return item;
    }
    ++it;
  }
  return NULL;
}

void LogWidget::clear()
{
  Q3ListViewItemIterator it((Q3ListView*)this);
  while( it.current() )
  {
    LogLvi* item = (LogLvi*)it.current();
    if( item->isStopped() )
    {
      takeItem(item);
      delete item;
    }
    ++it;
  }

  for( int i = 0; i < columns(); i++ )
  {
    adjustColumn(i);
  }
}
