/***************************************************************************
 *   Copyright (C) 2007 by Anistratov Oleg                                 *
 *   ower86@gmail.com                                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License version 2        *
 *   as published by the Free Software Foundation;                         *
 *                                                                         *
 *   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.                          *
 *                                                                         *
 ***************************************************************************/
#include "usersstatisticswgt.h"

#include "userslist.h"
#include "usersstatisticsmodel.h"
#include "channelwgt.h"

#include <QHeaderView>

UsersStatisticsWgt::UsersStatisticsWgt(QWidget* parent) : QTableView(parent)
{
  setIconSize(QSize(32 + 16 + 16, 32));
  setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
}


UsersStatisticsWgt::~UsersStatisticsWgt()
{
}

void UsersStatisticsWgt::sortByColumn(int column)
{
  ((UsersStatisticsModel*)model())->sort(column, horizontalHeader()->sortIndicatorOrder());
  emit sorted();
}

QByteArray UsersStatisticsWgt::saveState()
{
  // Format:
  // 1 byte - sorting column
  // 1 byte - sorting order
  // 1xcolumnsCount :
  // 1 byte - columnID
  // 2 bytes - columnWidth

  UsersStatisticsModel* mdl = (UsersStatisticsModel*)model();
  QByteArray state;
  char arr2[2];

  if(mdl)
  {
    state.append(char(mdl->sortingColumn()));
    state.append(char(mdl->sortOrder()));

    for(int i = 0; i < mdl->columnsCount(); i++)
      if(mdl->columnID(i) != UsersStatisticsModel::Invalid)
      {
        catUS2str(arr2, columnWidth(i));
        state.append(mdl->columnID(i));
        state.append(arr2[0]);
        state.append(arr2[1]);
      }
  }

  return state;
}

void UsersStatisticsWgt::restoreState(const QByteArray & state)
{
  UsersStatisticsModel* mdl = (UsersStatisticsModel*)model();
  char arr2[2];
  Qt::SortOrder order;
  int column;

  if(mdl)
  {
    if(state.size() >= 3)
      mdl->clearColumns();

    column = state.at(0);
    order  = Qt::SortOrder(state.at(1));

    for(int i = 0, j = 2; ; i++)
    {
      if(j + 3 > state.size())
        break;

      mdl->addColumn(state.at(j++));
      arr2[0] = state.at(j++);
      arr2[1] = state.at(j++);

      setColumnWidth(i, str2US(arr2));
    }

    mdl->setSortingColumn(column);
    mdl->setSortOrder    (order);

    horizontalHeader()->setSortIndicator(column, order);
  }
}
