//
// C++ Implementation: c6contactlistitem
//
// Description:
//
//
// Author: Giorgio Alfarano <openc6@hotmail.com>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "c6contactlistitem.h"
#include "c6settings.h"
#include "c6global.h"
#include <qfontmetrics.h>
#include <qpainter.h>
#include <qpixmap.h>
#include <qimage.h>
#include "c6proto.h"

// this code is taken from Qt Trolltech source
// qlistview.cpp
// QT BEGIN

static QString qEllipsisText( const QString &org, const QFontMetrics &fm, int width, int align )
{
    int ellWidth = fm.width( "..." );
    QString text = QString::fromLatin1("");
    int i = 0;
    int len = org.length();
    int offset = (align & Qt::AlignRight) ? (len-1) - i : i;
    while ( i < len && fm.width( text + org[ offset ] ) + ellWidth < width ) {
        if ( align & Qt::AlignRight )
            text.prepend( org[ offset ] );
        else
            text += org[ offset ];
        offset = (align & Qt::AlignRight) ? (len-1) - ++i : ++i;
    }
    if ( text.isEmpty() )
        text = ( align & Qt::AlignRight ) ? org.right( 1 ) : text = org.left( 1 );
    if ( align & Qt::AlignRight )
        text.prepend( "..." );
    else
        text += "...";
    return text;
}

// QT END


C6ContactListItem::C6ContactListItem(QListViewItem *root,QString const &nick, QString const& message):
        QListViewItem(root),
        _listViewItem(root),
        _isGroup(false),
        _nick(nick),
        _message(message)
{}

C6ContactListItem::C6ContactListItem(QListView* parent,QListViewItem* root,bool isGroup):
        QListViewItem(parent,root),
        _listViewItem(0),
        _isGroup(isGroup)
{
    Q_ASSERT(isGroup);
}

bool C6ContactListItem::isGroup() const
{
    return _isGroup;
}
        
const QString& C6ContactListItem::getNick() const
{
    return (_nick);     
}            

int C6ContactListItem::compare( QListViewItem *i, int col,bool ascending ) const
{
    int ret;
    C6ContactListItem* tmp = static_cast<C6ContactListItem*>(i);
    if (col == 1)
    {
        ret = getNick().compare(tmp->getNick());
    }
    else
    {
        ret = QListViewItem::compare(i,col,ascending);
    }

    return(ret);
}

void C6ContactListItem::setup()
{
    const float ROW_WEIGHT = 2.3;   
    QFont font = listView()->font();
    QFontMetrics fm(font);

    if (parent() != 0)
    {
        setHeight(ROW_WEIGHT*fm.height());
    }
    else
    {
        QListViewItem::setup();
    }
}


// part of paintCell code is taken from Qt Trolltech source
// qlistview.cpp

void C6ContactListItem::paintCell( QPainter * p, const QColorGroup & cg,
                int column, int width, int align )
{
    static const float COLUMN_WIDTH_RATIO = 1.4;    
    if (p != 0)
    {          
        if (column == 0)
        {
            QListView *lv = listView();
            if (lv != 0)
            {
                QFontMetrics fm( p->fontMetrics() );
                QFont font = p->font();
        
                lv->setColumnWidth(0,lv->width()/COLUMN_WIDTH_RATIO);
                            
                int marg = lv->itemMargin();
                int r = marg;
                const QPixmap* icon = pixmap( column );
        
                const BackgroundMode bgmode = lv->viewport()->backgroundMode();
                const QColorGroup::ColorRole crole = QPalette::backgroundRoleFromMode( bgmode );
                            
                p->fillRect( 0, 0, width, height(), cg.brush( crole ) );
                    
                if ( isSelected() &&
                    (column == 0 || lv->allColumnsShowFocus()) )
                {
                    p->fillRect( r - marg, 0, width - r + marg, height(),
                                cg.brush( QColorGroup::Highlight ) );
                    if ( isEnabled() || !lv )
                    {                  
                        p->setPen( cg.highlightedText() );
                    }                  
                    else 
                    if ( !isEnabled() && lv)
                    {                     
                        p->setPen( lv->palette().disabled().highlightedText() );
                    }                  
                }
                else
                {
                    if ( isEnabled() || !lv )
                    {                  
                        p->setPen( cg.text() );
                    }                  
                    else 
                    if ( !isEnabled() && lv)
                    {                     
                        p->setPen( lv->palette().disabled().text() );
                    }                  
                }
        
                bool reverse = FALSE;
                int iconWidth = 0;
        
                if ( icon )
                {
                    iconWidth = icon->width() + lv->itemMargin();
                    int xo = r;
                        // we default to AlignVCenter.
                    int yo = ( height() - icon->height() ) / 2;
        
                        // I guess we may as well always respect vertical alignment.
                    if ( align & AlignBottom )
                    {                  
                        yo = height() - icon->height();
                    }                  
                    else 
                    if ( align & AlignTop )
                    {                     
                        yo = 0;
                    }                  
                    
                    if ( reverse )
                    {                  
                        xo = width - 2 * marg - iconWidth;
                    }                  
                    p->drawPixmap( xo, yo, *icon );
                }
        
                if ( !(align & AlignTop || align & AlignBottom) )
                {               
                    align |= AlignVCenter;
                }               
        
                if ( !reverse )
                {
                    r += iconWidth;
                }
        
        
                C6Settings &settings = C6Settings::getInstance();
                int y = fm.ascent();
        
                if (parent() == 0)
                {
                    p->setPen(QColor(settings.getContactGroupForeColor()));
                    font.setBold(true);
                    p->setFont(font);
                    p->drawText( r,0, width-marg-r, height(), align,text(column));
                }
                else
                {
                    if (_nick.length() > 0)
                    {
                        p->drawText(r,-y+1,width-marg-r,height(),align,_nick);
                    }
        
                    if (_message.length() > 0)
                    {
                        int pw = lv->itemMargin()*2 - fm.minLeftBearing() - fm.minRightBearing();
                        pw += pixmap( column ) ? pixmap( column )->width() + lv->itemMargin() : 0;
                            
                        QString text;
                        if (fm.width(_message) + pw > width ) 
                        {
                            text = qEllipsisText(_message, fm, width - pw, align);
                        }
                        else
                        {
                            text = _message;    
                        }                      
                            
                        font.setItalic(true);
                        p->setFont(font);
                        p->setPen(QColor(settings.getContactGroupForeColor()));
                        p->drawText(r,height()-4,text);
                    }
        
                    p->setPen(QColor(USER_COLOR_BACK));
                    p->drawLine(0,height()-1,width,height()-1);
                }
            }         
        }
        else
        {
            listView()->setColumnWidth(1,DEFAULT_PHOTO_WIDTH);  
            p->save();              
            QListViewItem::paintCell(p,cg,column,width,align);
            if (parent() != 0)
            {                
                p->setPen(QColor(USER_COLOR_BACK));
                p->drawLine(0,height()-1,width,height()-1);         
            }                
            
            p->restore();    
        }
    }   
}


void C6ContactListItem::paintBranches(QPainter * p, const QColorGroup & cg, int w, int y, int h )
{
    p->eraseRect (0,0,w,h);
}

void C6ContactListItem::paintFocus ( QPainter * p, const QColorGroup & cg, const QRect & r )
{
}    

C6ContactListTip::C6ContactListTip(QListView* parent) : QToolTip(parent->viewport()),
        _parent(parent)
{}
        
void C6ContactListTip::maybeTip(const QPoint & pos)
{
    C6ContactListItem *it = dynamic_cast<C6ContactListItem*>(_parent->itemAt(pos));

    if (it != 0)
    {
        if (it->isGroup() == false)
        {
            C6Global &global = C6Global::getInstance();
            QStringList groups = global.getAllGroups();
            QString nick = it->getNick();
            C6Users* tmp = 0;

            for (unsigned int i=0; i < groups.count(); i++)
            {
                bool found = false;
                C6Users::C6UsersList &netFriend = global.getC6UsersFromGroup(groups[i]);
                for (tmp = netFriend.first(); tmp; tmp = netFriend.next())
                {
                    if(tmp->getNick() == nick)
                    {
                        found = true;
                        break;
                    }
                }

                if (found == true)
                {
                    break;
                }
            }
           
               
            QFontMetrics fm(_parent->font());    
            QString tipText = "<table><tr><td width = "+
                    QString::number(fm.width("Messaggio:")*2)+"><b>Nick:</b> </td><td>"+nick+"</td></tr>";
            
            const char* statusStr = C6Proto::getStatusString(C6Proto::mapUS2PS(tmp->getStatus()));
            QString maxString;
            
            if (statusStr != 0)
            {  
                QString tmp = QString(statusStr);     
                tipText += "<tr><td><b>Stato:</b> </td><td>"+tmp+"</td></tr>";
                maxString = tmp;    
            }            
                     
            if (tmp->getDailyMessage().length() > 0)
            {
                if (tmp->getDailyMessage().length() >  maxString.length())
                {
                    maxString = tmp->getDailyMessage();               
                }               
                tipText+= "<tr><td><b>Messaggio: </b></td><td width ="+
                        QString::number(fm.width(maxString)*1.2)+">"+tmp->getDailyMessage()+"</td></tr>";
            }         
            
            tipText+="</table>";
            tip(_parent->itemRect(it),tipText);
        }
    }
}      
