/***************************************************************************
 *   Copyright (C) 2005 by yunfan                                          *
 *   yunfan_zg@163.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.             *
 ***************************************************************************/

#include "evachatview.h"
#include "evahtmlparser.h"
#include "evaresource.h"
#include "../evamain.h"
#include <qstringlist.h>
#include <qtimer.h>
#include <qpopupmenu.h>
#include <qclipboard.h>
#include <qdragobject.h>
#include <kaction.h>
#include <qapplication.h>
#include <kapplication.h>
#include <klocale.h>

EvaChatView::EvaChatView( QWidget * parent, const char * name )
	: KHTMLPart(parent, name), menu(NULL), buffer(""), 
	lastHeight(0)
{
	//setOnlyLocalReferences(true);
	//if(menu) delete menu;
	menu = new QPopupMenu(0, "popup");
	copyAction  = KStdAction::copy( this, SLOT(copy()), actionCollection());
	copyAction->plug( menu );
	setDNDEnabled(true);
	setAutoloadImages(true);
	view()->setHScrollBarMode(QScrollView::AlwaysOff);
	
	//setStandardFont("Helvetica");
	//buffer += "<body style=\"font-size:9pt;font-family:Helvetica\">";
	QObject::connect(this, SIGNAL(selectionChanged()), SLOT(slotSelectionChanged()));
	QObject::connect(this, SIGNAL(popupMenu(const QString &, const QPoint &)), 
			SLOT(slotPopupMenu(const QString &, const QPoint &)));
	QObject::connect(browserExtension(), SIGNAL(openURLRequest(const KURL &, const KParts::URLArgs &)), 
			SLOT(slotLinkClicked( const KURL &)));
}

EvaChatView::~EvaChatView()
{
	delete menu;
}

QString EvaChatView::wrapFontAttributes(QColor color, Q_UINT8 size,
                                            bool underline, bool italic, bool bold,
                                            QString contents)
{
	QString fontHead = "<span style=\"";
	QString fontSize = "font-size: "+QString::number(size)+"pt; ";
	
	QString colorStr="";
	for(uint i=0; i<6; i++){
		Q_UINT8 num =(color.rgb()>>(5-i)*4)&0x0000000f; 
		colorStr+=QString("%1").arg(num,1,16);
	}
	QString fontColor = QString("color: #") + colorStr + QString("\" >");
	
	QString fontStye = "", fontStyeEnd="";
	if(bold){
		fontStye+="<b>";
		fontStyeEnd+="</b>";
	}
	if(italic){
		fontStye+="<i>";
		fontStyeEnd="</i>" + fontStyeEnd;
	}
	if(underline){
		fontStye+="<u>";
		fontStyeEnd="</u>" + fontStyeEnd;
	}
	QString fontEnd = "</span>";
	QString ret = fontHead + fontSize + fontColor + fontStye + contents + fontStyeEnd + fontEnd;
	return ret;
}

QString EvaChatView::wrapNickName(QString &nick, QDateTime time, QColor color, bool isNormal)
{
	QString colorStr="";
	for(uint i=0; i<6; i++){
		Q_UINT8 num =(color.rgb()>>(5-i)*4)&0x0000000f; 
		colorStr+=QString("%1").arg(num,1,16);
	}
	QString fontColor = QString("color: #") + colorStr + QString("\" >");
		
	QString htmlName = nick;
	EvaHtmlParser parser;
	parser.setAbsImagePath(EvaMain::images->getSmileyPath());
	parser.convertToHtml(htmlName, false, true);
	QString msg = "<span style=\"font-size: 9pt; color: #" + colorStr +"\"><b>" + htmlName + "</b> ";
	if(!isNormal)
		msg+=i18n("(Auto-Reply)");
	
	msg+=" "+time.toString("yyyy-MM-dd hh:mm:ss") + "</span><br>";
	return msg;
}

void EvaChatView::append( QString & nick, QDateTime time, QColor nameColor, bool isNormal, 
				QColor msgColor, Q_UINT8 size, 
				bool underline, bool italic, bool bold, QString contents )
{
	QString msg = wrapNickName(nick, time, nameColor, isNormal) + 
			wrapFontAttributes(msgColor, size, underline, italic, bold, contents);
	buffer += (msg + "<br>");
	begin();
	write(buffer);
	write("</body>");
	end();
	
	lastHeight = view()->contentsHeight();
	QTimer::singleShot(20, this, SLOT(slotScrollToBottom()));
}

void EvaChatView::updatePicture( const QString filename , const QString tmpFileName)
{
	buffer.replace(tmpFileName, filename);
	begin();
	write(buffer);
	write("</body>");
	end();
	
	lastHeight = view()->contentsHeight();
	QTimer::singleShot(20, this, SLOT(slotScrollToBottom()));
}

void EvaChatView::slotScrollToBottom()
{
	if( view()->contentsHeight() == lastHeight){	
		QTimer::singleShot(20, this, SLOT(slotScrollToBottom()));
	}else{
		view()->setContentsPos(view()->contentsX(), view()->contentsHeight() - view()->visibleHeight() );
		lastHeight = view()->contentsHeight();
	}
}

void EvaChatView::slotLinkClicked( const KURL & url)
{
	QStringList args;
	QString cmd = url.url();
	args<<"exec"<< cmd;
	kapp->kdeinitExec("kfmclient",args);
}

void EvaChatView::slotPopupMenu( const QString & , const QPoint & point )
{
	//copyAction->setEnabled( hasSelection() );
	menu->popup(point);
}

void EvaChatView::copy( )
{
	if(hasSelection()){
		QString text = selectedText();
		QApplication::clipboard()->setText( text, QClipboard::Clipboard );
		QApplication::clipboard()->setText( text, QClipboard::Selection );
	}
}

// it seems this method doesn't do the job
void EvaChatView::startDrag( )
{
	QDragObject *d = new QTextDrag(selectedText(), view());
	d->dragCopy();
}

void EvaChatView::slotSelectionChanged( )
{
	copyAction->setEnabled( hasSelection() );
}



