/***************************************************************************
 *   Copyright (C) 2007 by Anistratov Oleg                                 *
 *   ower@users.sourceforge.net                                            *
 *                                                                         *
 *   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 "userslistwgt.h"
#include "globals.h"

#include <QLayout>
#include <QLabel>
#include <QIcon>
#include <QPixmap>
#include <QSize>
#include <QFont>

#include "singlemessagewgt.h"
#include "userwgt.h"
#include "userinfo.h"
#include "qchaticon.h"
#include "userlisticonformat.h"

#include "qchatsettings.h"

UsersListWgt::UsersListWgt(QWidget *parent)
 : QListWidget(parent)
{
  m_menu             = new QMenu  (this);
  m_singleMessageAct = new QAction(this);
  m_showInfoAct      = new QAction(this);
  m_sendFileAct      = new QAction(this);
  m_privateChatAct   = new QAction(this);

  m_menu->addAction(m_singleMessageAct);
  m_menu->addAction(m_sendFileAct);
  m_menu->addAction(m_privateChatAct);

  // FIXME move to setIcons ":/
  m_sendFileAct     ->setIcon(QChatIcon::icon("send-file"));
  m_singleMessageAct->setIcon(QChatIcon::icon("private-message"));
  m_privateChatAct  ->setIcon(QChatIcon::icon("private-chat"));

  connect(m_singleMessageAct, SIGNAL(triggered(bool)),
          this              , SLOT  (slot_singleMessage()));

  connect(m_sendFileAct     , SIGNAL(triggered(bool)),
          this              , SLOT  (slot_sendFile()));

  connect(m_privateChatAct  , SIGNAL(triggered(bool)),
          this              , SLOT  (slot_privateChat()));

  connect(this              , SIGNAL(     itemDoubleClicked(QListWidgetItem*)),
          this              , SLOT  (send_itemDoubleClicked(QListWidgetItem*)));

  setIconSize(QSize(QChatSettings::settings()->iconFormat()->totalWidth(),
                    QChatSettings::settings()->iconFormat()->totalHeight()));

  setSortingEnabled(true);

  setMouseTracking(true);
  setAcceptDrops(true);

  retranslate();
}
//\*****************************************************************************
UsersListWgt::~UsersListWgt()
{
  qDebug("[~UsersListWgt]\n");
}
//\*****************************************************************************
void UsersListWgt::retranslate()
{
  m_singleMessageAct->setText(tr("Send Single Message.."  ));
  m_showInfoAct     ->setText(tr("Show User Information.."));
  m_sendFileAct     ->setText(tr("Send File.."));
  m_privateChatAct  ->setText(tr("Private Chat.."));
}
//\*****************************************************************************
void UsersListWgt::addUser(UserWgt* user)
{
  QFont fnt;

  Q_ASSERT(NULL != user);

  if(user->info())
  {
    qDebug("[UsersListWgt::addUser]: status = %d", user->info()->status());

    if(user->info()->status() == Globals::FREE || user->info()->status() == Globals::READY4CHAT)
      fnt.setBold(true);

    user->setFont(fnt);

    user->setText(QChatSettings::settings()->iconFormat()->text().
                  replace(QRegExp("%nick")      , user->info()->nickname()).
                  replace(QRegExp("%compname")  , user->info()->compName()).
                  replace(QRegExp("%firstname") , user->info()->firstName()).
                  replace(QRegExp("%lastname")  , user->info()->lastName()).
                  replace(QRegExp("%secondname"), user->info()->secondName()).
                  replace(QRegExp("%version")   , user->info()->programVerName()).
                  replace(QRegExp("%uid")       , QString("%1").arg(user->info()->uid())).
                  replace(QRegExp("%ip")        , QHostAddress(user->info()->ip()).toString()));
  }

  if(row(user) >= 0)
    setItemHidden(user, false);
  else
    addItem(user);

  user->setSizeHint(QSize(1, QChatSettings::settings()->iconFormat()->totalHeight()));

  qDebug("[UsersListWgt::addUser]: added: '%s'", user->text().toLocal8Bit().data());
}
//\*****************************************************************************
void UsersListWgt::hideUser(UserWgt* user)
{
  takeItem(row(user));
}
//\*****************************************************************************
void UsersListWgt::clear()
{
  int cnt = count();
  UserWgt* item_;

  while(count() || cnt)
  {
    item_ = (UserWgt*)item(0);

    if(NULL != item_)
    {
      item_->setText("");
      takeItem(0);
    }

    --cnt;
  }
}
//\*****************************************************************************
void UsersListWgt::slot_singleMessage()
{
  UserWgt*          usr = (UserWgt*)(currentItem());
  SingleMessageWgt* smw = new SingleMessageWgt(QString(tr("Message to ")) + usr->info()->nickname(),
                                               "",
                                               usr->info()->uid(),
                                               QHostAddress(usr->info()->ip())
                                               );

  connect(smw , SIGNAL(singleMessage    (QString, quint64, bool)),
          this, SIGNAL(singleMessage    (QString, quint64, bool)));

  smw->show();
}
//\*****************************************************************************
void UsersListWgt::slot_sendFile()
{
  UserWgt* usr = (UserWgt*)(currentItem());

  if(usr)
    emit wantSendFile(usr->info()->uid());
}
//\*****************************************************************************
void UsersListWgt::mousePressEvent (QMouseEvent * ev)
{
  int i;
  int nitems   = 0;
  int cnt      = count();
  int height   = 0;

  for(i = 0; i < cnt; i++)
    if(!isItemHidden(item(i)))
      nitems++;

  if(nitems)
    height = (item(0)->sizeHint().height()) * nitems;

  if(ev->button() == Qt::RightButton && currentItem() && isItemSelected(currentItem()) &&
    !isItemHidden(currentItem())     && ev->y() < height )
  {
//     UserWgt* usr = (UserWgt*)(currentItem());
//     m_privateChatAct  ->setText((tr("Private Chat with ") + usr->info()->nickname()));
//     m_sendFileAct     ->setText((tr("Send File to "     ) + usr->info()->nickname()));
//     m_singleMessageAct->setText((tr("Single Message to ") + usr->info()->nickname()));
    m_menu->popup(ev->globalPos());
  }

  QListWidget::mousePressEvent(ev);
}
//\*****************************************************************************
void UsersListWgt::slot_privateChat()
{
  UserWgt* usr = (UserWgt*)(currentItem());

  if(usr)
    emit wantPrivateChat(usr->info()->nickname(), usr->info()->uid());
}
//\*****************************************************************************
void UsersListWgt::send_itemDoubleClicked(QListWidgetItem* item)
{
  emit itemDoubleClicked((UserWgt*)item);
}

void UsersListWgt::dropEvent(QDropEvent * ev)
{
  ev->acceptProposedAction();
  qDebug("[UsersListWgt::dropEvent]: data = %s\n", ev->mimeData()->text().toLocal8Bit().data());
}

void UsersListWgt::dragEnterEvent(QDragEnterEvent * ev)
{
  ev->acceptProposedAction();
}

void UsersListWgt::dragMoveEvent(QDragMoveEvent * ev)
{
ev->acceptProposedAction();

}
