/* ====================================================================
 * Copyright (c) 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 "ListViewHeaderHandler.h"
#include "Settings.h"
#include "sublib/settings/LayoutSettings.h"

// qt
#include <Qt3Support/Q3Header>

// sys
#include <vector>

typedef std::vector<Q3Header*> Header;

class ListViewHeaderHandler::Data
{
public:
  Header items;
};

ListViewHeaderHandler::ListViewHeaderHandler()
{
  _data = new ListViewHeaderHandler::Data();
}

ListViewHeaderHandler::~ListViewHeaderHandler()
{
  delete _data;
}

void ListViewHeaderHandler::add( Q3Header* h )
{
  connect( h, SIGNAL(sizeChange(int,int,int)), this, SLOT(sizeChanged(int,int,int)) );
  connect( h, SIGNAL(indexChange(int,int,int)), this, SLOT(indexChanged(int,int,int)) );

  _data->items.push_back(h);
}

void ListViewHeaderHandler::del( Q3Header* h )
{
  for( Header::iterator it = _data->items.begin(); it != _data->items.end(); it++ )
  {
    if( (*it) == h )
    {
      disconnect( h, SIGNAL(sizeChange(int,int,int)), this, SLOT(sizeChanged(int,int,int)) );
      disconnect( h, SIGNAL(indexChange(int,int,int)), this, SLOT(indexChanged(int,int,int)) );
      _data->items.erase(it);
      return;
    }
  }
}

void ListViewHeaderHandler::sizeChanged( int section, int oldSize, int newSize )
{
  // sender is a QHeader
  const QObject* src = sender();

  for( Header::iterator it = _data->items.begin(); it != _data->items.end(); it++ )
  {
    if( (*it) == src )
      continue;

    (*it)->blockSignals(true);
    (*it)->resizeSection( section, newSize );
    (*it)->blockSignals(false);
  }

  Settings s;
  s.layout().setHeaderColumns( src->parent()->name(), (Q3Header*)src );
}

void ListViewHeaderHandler::indexChanged( int section, int fromIndex, int toIndex )
{
  // sender is a QHeader
  const QObject* src = sender();

  for( Header::iterator it = _data->items.begin(); it != _data->items.end(); it++ )
  {
    if( (*it) == src )
      continue;

    (*it)->blockSignals(true);
    (*it)->moveSection( section, toIndex );
    (*it)->blockSignals(false);
  }

  Settings s;
  s.layout().setHeaderColumns( src->parent()->name(), (Q3Header*)src );
}
