/***************************************************************************
                          c6profile.cpp  -  description
                             -------------------
    begin                : Fri Nov 14 2003
    copyright            : (C) 2003 by Giorgio A.
    email                : openc6@hotmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/


#include "c6profile.h"
#include <qlabel.h>
#include <qrect.h>
#include <qdatetime.h>
#include <qhostaddress.h>
#include <qgroupbox.h>
#include <qcolor.h>
#include <qfont.h>
#include <qtextedit.h>
#include <qlayout.h>
#include <qtooltip.h>
#include "c6button.h"
#include "c6settings.h"
#include "c6global.h"
#include "qstringlist.h"
#include "c6pixmapcache.h"
#include "c6proto.h"
#include "c6utils.h"

#define XLABEL 10
#define YLABEL 7
#define HLABEL 18
#define DLABEL 5
#define WLABEL_1 180
#define WLABEL_2 250
#define YLABEL_2 6

#define PROFILE_STR "Profilo di "
#define COMBO_CLIENT_TYPE 0x0e

static const char* statusTextLabel[4] =
    {"Stato","Indirizzo IP","Versione client","Connesso dalle"
    };
static const char* textSearchString[MAXCOMBO]=
    {"Età","Genere","Occupazione","Area Geografica",
     "Regione/Provincia","Hobby","Sport Praticati",
     "Genere Musicale","Genere Cinematografico","Odi Cordiali"
    };

static QString getValueFromKey(QString const & item)
{
    return(item.section("=",1,1));
}

static unsigned char toSkip(int id)
{
    const int maxIndex = MAXCOMBO+5;
    const unsigned char ftrans[maxIndex]=
        {
            0,1,255,2,3,4,5,6,7,8,255,9,255,255,255
        };

    return(id < maxIndex ? ftrans[id] : 255);
}

/*!
    \fn getStatusStr(int status)
 */
QString getStatusStr(unsigned char status)
{
    QString str;

    switch (status & 7)
    {
        case C6Proto::PUBLIC_C6:
        str = "Pubblica C6";
        break;
        case C6Proto::PUBLIC_NET:
        str = "Pubblica netfriend";
        break;
        case C6Proto::PRIVATE_NET:
        str = "Privata netfriend";
        break;
    default:
        str = "Privata C6";
    }

    return(str);
}

C6Profile::C6Profile(QWidget *parent, const char *name ) : profile(parent,name)
{
    QLabel *tmp=0;

    for (int i=0; i < MAXCOMBO; i++)
    {
        profileResult[i] = new QLabel(profileInfo);
        profileResult[i]->setPaletteForegroundColor(QColor(3,118,231));
        profileResult[i]->setBackgroundOrigin(QWidget::AncestorOrigin);
        profileResult[i]->setGeometry(QRect(XLABEL+210,i*(HLABEL+DLABEL)+YLABEL,WLABEL_2,HLABEL));

        tmp = new QLabel(profileInfo);
        tmp->setPaletteForegroundColor(QColor("Black"));
        tmp->setBackgroundOrigin(QWidget::AncestorOrigin);
        tmp->setText(QString::fromUtf8(textSearchString[i])+QString(":"));
        tmp->setGeometry(QRect(XLABEL,i*(HLABEL+DLABEL)+YLABEL,WLABEL_1,HLABEL));
    }

    for(int i=0; i < MAXEXTENDED; i++)
    {
        tmp = new QLabel(furtherInfo);
        tmp->setPaletteForegroundColor(QColor("Black"));
        tmp->setBackgroundOrigin(QWidget::AncestorOrigin);
        tmp->setText(statusTextLabel[i]+QString(":"));
        tmp->setGeometry(QRect(XLABEL,i*(HLABEL+1)+YLABEL_2,WLABEL_1,HLABEL));

        extendedInfo[i] = new QLabel(furtherInfo);
        extendedInfo[i]->setPaletteForegroundColor(QColor(3,118,231));
        extendedInfo[i]->setBackgroundOrigin(QWidget::AncestorOrigin);
        extendedInfo[i]->setGeometry(QRect(XLABEL+210,i*(HLABEL+1)+YLABEL_2,WLABEL_2,HLABEL));
    }

    C6Global &global = C6Global::getInstance();
    QString path = global.getSkinPath();

    exitButtonPlaceHolder->hide();
    C6Button *exitButton = new C6Button(frame15,0,0,path+"chat_71.png",path+"chat_over_109.png");
    layout22->addWidget(exitButton);
    connect(exitButton,SIGNAL(clicked()),this,SLOT(deleteLater()));
    
    QWidget *upParent = reinterpret_cast<QWidget*>(aboutButtonPlaceHolder->parent());
    C6Button* aboutButton = new C6Button(upParent,0,0,path+"chat_68.png",
                                         path+"chat_over_68.png",
                                         path+"chat_over_68.png");
    QToolTip::add
            (aboutButton,"Informazioni su OpenC6");
    aboutButtonPlaceHolder->hide();
    layout23->addWidget(aboutButton);   
    connect(aboutButton,SIGNAL(clicked()),this,SLOT(aboutClicked()));  
    setCustomFont();    
}
C6Profile::~C6Profile()
{
    //all objects are automatically destoyed by qt
}

void C6Profile::updateUserProfile(unsigned char *data,int packL)
{
    QString tmp;
    int time=0;
    int temp=0;
    QDateTime date;
    QHostAddress ip;
    
    const unsigned char* maxPtr = data+packL;
    
    int len = *data; 
    unsigned char* tmpStr = new unsigned char[len];    
    C6Utils::safeStringCopy(tmpStr,data+1,len,maxPtr);    
    nickLabel->setText(tmp.setAscii((const char*)tmpStr,len));
    delete [] tmpStr;
    
    data+=len+1;
    C6Utils::safeShortRead(data,&temp,maxPtr);
    C6Utils::safeShortRead(data+2,&time,maxPtr);
    time |= (temp << 16);
    data+=4;
    date.setTime_t(time,Qt::LocalTime);
    extendedInfo[3]->setText(date.toString("hh:mm:ss"));

    C6Utils::safeShortRead(data,&temp,maxPtr);
    C6Utils::safeShortRead(data+2,&time,maxPtr);
    time |= (temp << 16);
    ip.setAddress(time);
    extendedInfo[1]->setText(ip.toString());

    data+=4;

    C6Utils::safeByteRead(data,&temp,maxPtr);
    data++;

    if (temp >=0)
    {
        extendedInfo[0]->setText(C6Proto::getStatusString(temp));
    }
    else
    {
        extendedInfo[0]->setText("");
    }

    const unsigned char* dataPost = setProfileResult(data,maxPtr);
    
    int newStatus = C6Proto::FREE;
    QVariant variantData;
    int numVariant = 0;        
    int x = 0;
    
    do         
    {     
        bool ok=false;        
        dataPost+=C6Proto::parseAggregate(const_cast<unsigned char*>(dataPost),maxPtr,numVariant,variantData);
        int dataInt = variantData.toInt(&ok);
                
        if (ok == true)
        {
            newStatus = dataInt;        
        }
        x++;    
                    
    } while (x < numVariant);      
   
    extendedInfo[0]->setText(C6Proto::getStatusString(newStatus));
    setCaption(QString(PROFILE_STR)+nickLabel->text());   
}

void C6Profile::closeEvent(QCloseEvent *e)
{
    e->accept();
    deleteLater();
}

/*!
    \fn C6Profile::setProfileResult(unsigned char *data)
 */
const unsigned char* C6Profile::setProfileResult(const unsigned char *data,const unsigned char* maxPtr)
{
    int combono=0;
    int subid=0;
    unsigned char skip=0;
    int temp=0;
    QString globalStr,combostr;

    int oldcombono = 255;

    for(unsigned int i=0; i < MAXCOMBO; i++)
    {
        profileResult[i]->setText("");
    }

    C6Utils::safeShortRead(const_cast<unsigned char*>(data),&temp,maxPtr);
    data+=2;

    C6Global &global = C6Global::getInstance();
    
    for (int i=0; i < temp; i++)
    {
        C6Utils::safeByteRead(const_cast<unsigned char*>(data),&combono,maxPtr);   
        combono--;    
        C6Utils::safeByteRead(const_cast<unsigned char*>(data+1),&subid,maxPtr);
        data+=2;
        combostr.sprintf("%02d",combono);

        skip = toSkip(combono);
       
        if (skip == 255)                // handle special case to take into account 
                                        // last c6 impl.  
        {   
            if (combono == COMBO_CLIENT_TYPE)
            {   
                const QString OPENC6_CLIENT = "OpenC6 (Linux/Mac)";
                const QString WINDOWS_C6_CLIENT = "C6 (Windows)";
                QString clientVersion;        
                if(subid == 2)
                {
                    clientVersion = OPENC6_CLIENT;               
                }
                else
                {
                    clientVersion = WINDOWS_C6_CLIENT;     
                }                                   
                extendedInfo[2]->setText(clientVersion);     
            }            
            continue;
        }         

        int loc_index = global.getProfileEntryIndex(global.getProfile(),"Profilo-"+combostr);

        if (loc_index != -1)
        {
            globalStr = getValueFromKey(global.getProfile()[loc_index+1+subid]);

            if (oldcombono == combono)
            {
                if (subid > 1)
                {
                    if (profileResult[skip]->text().stripWhiteSpace() != "")
                    {                  
                        globalStr.prepend(profileResult[skip]->text()+",");
                    }                  
                }
                else
                {
                    profileResult[skip]->setText("");
                }
            }
            profileResult[skip]->setText(globalStr);
        }
        oldcombono = combono;
    }
    return(data);   
}

/*!
    \fn C6Profile::setCustomFont()
 */
void C6Profile::setCustomFont()
{
    C6Global &global=C6Global::getInstance();      
    QFont lfont(global.getBaseFont());
    
    int size = lfont.pointSize()-1;
    
    if (size > 1)
    {
        lfont.setPointSize(size);
        setFont(lfont);      
    }   
}

void C6Profile::aboutClicked()
{
    emit showAbout();
}
    
