/***************************************************************************
 *   Copyright (C) 2004 by zsyddl                                          *
 *   morrowren@sina.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.                                   *
 *                                                                         *
 *   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.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
/*
	revised by yunfan  2005
	yunfan_zg@163.com
*/

#include "evadetailswindow.h"

#include "evaresource.h"
#include "../evamain.h"
#include "evapacket.h"
#include "evauser.h"
#include "evautil.h"
#include <qvariant.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qiconview.h>
#include <qradiobutton.h>
#include <qtextedit.h>
#include <qpixmap.h>
#include <qgroupbox.h>
#include <qmessagebox.h>
#include <qtimer.h>
#include <qstringlist.h>
#include <qtoolbutton.h>
#include <qtextcodec.h>
#include <kpushbutton.h>
#include <krun.h>
#include <klocale.h>
#include <kapplication.h>

//#include "../usermsg.ui.h"
/*
 *  Constructs a EvaDetailsWindow as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  TRUE to construct a modal dialog.
 */
 
EvaImageResource *EvaDetailsWindow::faces = NULL;
EvaDetailsWindow::EvaDetailsWindow(  QStringList &user, bool isMe,  QWidget* parent, const char* name, bool modal, WFlags fl)
	: EvaUserUIBase( isMe, parent, name, modal, fl ),
	details(user), isSelf(isMe), selectedFaceIndex(0), isSignatureChanged(false)
{
 
	// signals and slots connections
	QObject::connect( pB_Update, SIGNAL( clicked() ), this, SLOT( PB_UpdateInfor() ) );
	//connect( pB_UpdateQQShow, SIGNAL( clicked() ), this, SLOT( PB_UpdateQQShow() ) );
	
	QObject::connect( pB_Face, SIGNAL( clicked() ), this, SLOT( PLFaceClick() ) );
	QObject::connect( iV_Face, SIGNAL( doubleClicked(QIconViewItem*) ), this, SLOT( FaceChoose(QIconViewItem*) ) );
	QObject::connect( iV_Face, SIGNAL( clicked(QIconViewItem*) ), this, SLOT( FaceViewClicked(QIconViewItem*) ) );
	
	QObject::connect( kpbUpdateShow, SIGNAL( clicked() ), this, SLOT( PB_UpdateQQShow() ) );
	QObject::connect( tbtnShop, SIGNAL( clicked() ), this, SLOT( slotShopClicked() ) );
	QObject::connect( tbtnAlbum, SIGNAL( clicked() ), this, SLOT( slotAlbumClicked() ) );
	QObject::connect( tbtnHome, SIGNAL( clicked() ), this, SLOT( slotHomeClicked() ) );

	QObject::connect( teSignature, SIGNAL(textChanged()), SLOT(slotSignatureChanged()));
	
	if (!isSelf)
	{
		setCaption( i18n( "User Details" ) );
		tbtnShop->hide();
		tbtnAlbum->hide();
		tbtnHome->hide();
	}else{
		setCaption( i18n( "Modify User Details" ) );
		if(details.size()==37) pB_Update->setText( i18n( "Modify" ) );
		setupFaces();
	}	
	if(faces) pL_EvaQ->setPixmap(*(faces->getIcon("DETAILS_LOGO")));
	if(faces){
		QPixmap *icon = faces->getIcon("QQ_SHOP");
		if(icon)
			tbtnShop->setIconSet(QIconSet(*icon));
	} 
	if(faces){
		QPixmap *icon = faces->getIcon("QQ_ALBUM");
		if(icon)
			tbtnAlbum->setIconSet(QIconSet(*icon));
	}
	if(faces){
		QPixmap *icon = faces->getIcon("QQ_HOME");
		if(icon)
			tbtnHome->setIconSet(QIconSet(*icon));
	}
	UpdateData(true);
	if(details.size()!=37) {
		QTimer::singleShot(500, this, SLOT(slotFirstUpdate()));
	}
}

/*
 *  Destroys the object and frees any allocated resources
 */
EvaDetailsWindow::~EvaDetailsWindow()
{
    // no need to delete child widgets, Qt does it all for us
}

void EvaDetailsWindow::slotDetailsUpdated(QStringList list)
{
	if(details[0] != list[0] ) return;
	details = list;
	if(isSelf) pB_Update->setText( i18n( "Modify" ) );
	UpdateData(true);
}

void EvaDetailsWindow::slotBuddyQQShowReady(const int id)
{
	bool ok;
	int qq = details[0].toInt(&ok, 10);
	if(!ok) return;
	if(id != qq) return;
	QPixmap *pix = faces->getQQShow(id);
	if(pix){
		//pL_QQShow->setPixmap( *pix);
		lblQQShow->setPixmap( *pix);
	}
}

void EvaDetailsWindow::slotUpdateResult(bool ok, bool isSignature)
{
	if(ok)
		QMessageBox::information(this, i18n( "Modify Details"), i18n( "modify details successfully."));
	else
		QMessageBox::information(this, i18n( "Modify Details"), i18n( "failed to modify details."));
	if(isSignature && ok)
		isSignatureChanged=false;
}

void EvaDetailsWindow::slotSignatureReply(const bool ok)
{
	slotUpdateResult(ok, true);
}

void EvaDetailsWindow::setupFaces()
{
	if(!faces) return;
	iV_Face->clear();
	for(int i=1; i<102; i++){
		QIconViewItem *item =  new QIconViewItem( iV_Face, QString::null );
		item->setPixmap(*(faces->getFace(i)));
		item->setKey( QString::number(i));  // set face file index as key
	}
}

void EvaDetailsWindow::PB_UpdateInfor()
{
	bool ok;
	int id = details[0].toInt(&ok, 10);
	if(!ok) return;
	if ( !isSelf ){
		emit requestUpdate(id);
	}else{	
		if(UpdateData(false)){
			emit requestModify(details, leOldPwd->text(), leNewPwd->text());
			if(isSignatureChanged){
				QString contents = teSignature->text();
				if(contents.isEmpty()){
					emit requestDeleteSignature();printf("req delete sig\n");
				}else{
					emit requestUpdateSignature(contents);printf("req modify sig\n");
				}
			}
		}else
			emit requestUpdate(id);
	}
}


void EvaDetailsWindow::PB_UpdateQQShow()
{
	bool ok;
	int id = details[0].toInt(&ok, 10);
	if(ok)
		emit requestQQshow(id);
}


void EvaDetailsWindow::PLFaceClick()
{
	if(isSelf){
		if(iV_Face->isVisible()) 
			iV_Face->hide();
		else
			iV_Face->show();
	}
}


void EvaDetailsWindow::FaceChoose( QIconViewItem * item )
{
	if(!faces) return;
	selectedFaceIndex = faces->getFaceID(item->key().toInt());
	printf("select:%d, %d\n", selectedFaceIndex, item->key().toInt());
	pB_Face->setPixmap(*(item->pixmap()));
	iV_Face->hide();
}


void EvaDetailsWindow::FaceViewClicked( QIconViewItem * item )
{
    if ( item == NULL )
    {
	iV_Face->hide();
    }

}

bool EvaDetailsWindow::UpdateData(bool toShow)
{
	lE_Num->setText( details[0] );
	if(details.size()!=37) return false;

	bool OK;
	int id = details[0].toInt(&OK);
	if(!OK) return false;
	slotBuddyQQShowReady(id);
	
	const QQFriend *frd = (EvaMain::user->getFriendList()).getFriend(id); 
	int level = 0;
	QString signature = "";
	if(id == EvaMain::user->getQQ() ){
		level = EvaMain::user->getLevel();
		signature = QTextCodec::codecForName("GB18030")->toUnicode(EvaMain::user->getSignature().c_str());
	}else{
		if(frd){
			level = frd->getLevel();
			signature = QTextCodec::codecForName("GB18030")->toUnicode(frd->getSignature().c_str());
			teSignature->setReadOnly(true);
		}
	}
	int suns, moons, stars;
	EvaUtil::calcSuns(level, &suns, &moons, &stars);
	QString strSun =  "<img src=\"" + faces->getIconFullPath("TIME_SUN") + "\"></img>";
	QString strMoon = "<img src=\"" + faces->getIconFullPath("TIME_MOON") + "\"></img>";
	QString strStar = "<img src=\"" + faces->getIconFullPath("TIME_STAR") + "\"></img>";
	QString strLevel;
	for(int i=0; i<suns; i++){
		strLevel += strSun;
	}
	for(int i=0; i<moons; i++){
		strLevel += strMoon;
	}
	for(int i=0; i<stars; i++){
		strLevel += strStar;
	}
	lblLevelDisplay->setText("(" + QString::number(level) + ")" + strLevel);
	lblLevelDisplay->adjustSize();
	lE_Num->setReadOnly(true);
	if (toShow)
	{
		lE_Num->setText( details[0] );			
		lE_FName->setText( details[1]);
		lE_Age->setText( details[7] );
		cB_Sex->setCurrentText ( details[8] );
		cB_Area->setCurrentText( details[2]);
		cB_Covience->setCurrentText( details[3] ); 
		cB_City->setCurrentText( details[25] );
		
		bool ok;
		int faceId = details[21].toInt(&ok, 10);
		if(ok){
			selectedFaceIndex = faceId;
			QPixmap *pix = faces->getUserHeadPixmap(id);
			if(!pix) pix = faces->getFace(faces->getFaceFileIndex(faceId));
			if(pix) pB_Face->setPixmap( *pix );
		}else
			selectedFaceIndex = 0;

		lE_Email->setText( details[10] );
		lE_Addr->setText( details[5] );
		lE_MailNum->setText( details[4] );
        	lE_Phone->setText( details[6] );
		lE_MovePhone->setText( details[22]);
		
		lE_Name->setText( details[9]);
        	lE_School->setText( details[31] );
		cB_Job->setCurrentText( details[16] );
		lE_HPage->setText( details[17] );
		cB_ShX->setCurrentItem( details[33].toInt() );
		cB_BloodType->setCurrentItem(details[34].toInt());
		cB_Star->setCurrentItem( details[32].toInt() );
		tE_Text->setText( details[24] );
		teSignature->setText(signature);
		
		switch ( details[30].toInt() )
		{
			case 0: rB_Public->setChecked( true );
				break;
			case 1: rB_Protected->setChecked( true );
				break;
			case 2: rB_Private->setChecked( true );
				break;
			default:break;
		}
		QString authCode = details[18];
		if ( authCode == "0" ){
			rbtnAuthNoNeed->setChecked(true);
		}else if(authCode == "1"){
			rbtnAuthNeed->setChecked(true);
		}else if(authCode == "2") {
			rbtnAuthReject->setChecked(true);
		}		
	}
	else
	{
		if(gbChangePassword->isChecked()){
			if(leOldPwd->text().stripWhiteSpace() == ""){
				QMessageBox::information(this, i18n( "Modify Personal Details"), i18n( "enter your current password please.")); 
				leOldPwd->setFocus();
				return false;
			}
				
			if(leNewPwd->text() != leReNew->text()){
				QMessageBox::information(this, i18n( "Modify Personal Details"), i18n( "new password mismatch."));
				leReNew->setFocus(); 
				return false;
			}
			if(leNewPwd->text().stripWhiteSpace() == ""){
				QMessageBox::information(this, i18n( "Modify Personal Details"), i18n( "new password cannot be empty.")); 
				leNewPwd->setFocus();
				return false;
			}
		}
		details.clear();
		details.append(lE_Num->text( ));
		details.append(lE_FName->text( ));
		details.append(cB_Area->currentText(  ));
		details.append(cB_Covience->currentText( ));
		details.append(lE_MailNum->text( ));
		
		
		details.append(lE_Addr->text(  ));
        	details.append(lE_Phone->text(  ));
		details.append(lE_Age->text( ));
		details.append(cB_Sex->currentText(  )); 
		details.append(lE_Name->text(  ));
		
		details.append(lE_Email->text( ));
		details.append(""); // pagerSn
		details.append(""); // pagerNum
		details.append(""); // pagerSP
		details.append(""); // pagerBaseNum
		
		details.append(""); // pagerType
		details.append(cB_Job->currentText( ));
		details.append(lE_HPage->text(  ));
		if ( rbtnAuthNoNeed->isChecked() ){
			details.append("0");
		}else if ( rbtnAuthNeed->isChecked()){
			details.append("1");
		}else{
			details.append("2");
		}
		details.append(""); // unknown1
		
		details.append(""); // unknown2
		details.append( QString::number(selectedFaceIndex) ); 
		details.append(lE_MovePhone->text( ));
		details.append(""); // mobile type
		details.append(tE_Text->text(  ));
			
		details.append(cB_City->currentText(  ));
		details.append(""); // unknown3
		details.append(""); // unknown4
		details.append(""); // unknown5
		details.append(""); // open hp
		
		if ( rB_Public->isChecked() ){
			details.append("0");
		}else if ( rB_Protected->isChecked()){
			details.append("1");
		}else{
			details.append("2");
		}
        	details.append(lE_School->text( ));
		details.append(QString::number(cB_Star->currentItem(  )));
		details.append(QString::number(cB_ShX->currentItem(  )));
		details.append(QString::number(cB_BloodType->currentItem()));
		
		details.append(""); // qqshow
		details.append(""); // unknown6
	}
	return true;
}

void EvaDetailsWindow::slotFirstUpdate()
{
	bool ok;
	int id = details[0].toInt(&ok, 10);
	if(!ok) return;
	emit requestUpdate(id);
}

void EvaDetailsWindow::slotLinkClicked( const QString & url)
{
	QStringList args;
	args<<"exec"<< url;
	//kapp->kdeinitExec("kfmclient",args);
	KRun::runCommand("konqueror \""+url+"\"");
}

void EvaDetailsWindow::slotShopClicked( )
{
	QString url = "http://jump.qq.com/clienturl_simp_17?clientuin=" + QString::number(EvaMain::user->getQQ());
	url+="&clientkey=";
	url+=getClientKeyString();
	slotLinkClicked(url);
}

void EvaDetailsWindow::slotAlbumClicked( )
{
	QString url = "http://ptlogin.qq.com/qqshowalbum?clientuin=" + QString::number(EvaMain::user->getQQ());
	url+="&clientkey=";
	url+=getClientKeyString();
	slotLinkClicked(url);
}

void EvaDetailsWindow::slotHomeClicked( )
{
	QString url = "http://jump.qq.com/clienturl_42?clientuin=" + QString::number(EvaMain::user->getQQ());
	url+="&clientkey=";
	url+=getClientKeyString();
	slotLinkClicked(url);
}

const QString EvaDetailsWindow::getClientKeyString()
{
	QString key="";
	int len = Packet::getClientKeyLength();
	for(int i=0; i<len; i++){
		QString tmp = QString::number((unsigned char)(Packet::getClientKey()[i]), 16);
		if(tmp.length()==1)
			tmp = "0" + tmp;
		key+=tmp;
	}
	return key.upper();
}

void EvaDetailsWindow::slotSignatureChanged( )
{
	isSignatureChanged = true;
}

