/***************************************************************************
 *   author Michael Jarrett (JudgeBeavis@hotmail.com)                      *
 *   date April, 2004.                                                     *
 *                                                                         *
 *   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 "knateoncommon.h"
#include "networkwindow.h"

#include <qvbox.h>
#include <qdatetime.h>
#include <ktextedit.h>
#include <klocale.h>
#include <qcheckbox.h>

/*
 * I've tried to put this entire class in a big #ifdef block,
 * but moc doesn't seam to like that.
 */

// Create a non-modal dialog box with a close button, no main widget
// (we'll add one ourselves), and no separator.
// Display with NetworkWindow::show()
NetworkWindow::NetworkWindow(QWidget *parent, const char *name)
  : KDialogBase(parent, name, false, UTF8("Network Window"),
				KDialogBase::Close, KDialogBase::Close, false),
	m_nCapacity(10240), m_bShowIncoming(false), m_bShowOutgoing(false)
{

    // Dialog layout is a large text box in a vertical layout with another layout.
    // This second layout contains filter controls.
    // The Close button is at the bottom, and is managed by KDialogBase
    makeVBoxMainWidget();

    // Create main log
    m_pLogWidget = new KTextEdit(mainWidget());
    m_pLogWidget->setTextFormat(Qt::LogText);
    //m_pLogWidget->setReadOnly(true); // Handled by LogText mode

    // Create control filters
    QWidget *filterBox= new QVBox(mainWidget());
    m_pFilterIncomingWidget= new QCheckBox(UTF8("Show incoming server messages"), filterBox);
    m_pFilterIncomingWidget->setChecked(m_bShowIncoming);
    m_pFilterOutgoingWidget= new QCheckBox(UTF8("Show outgoing server messages"), filterBox);
    m_pFilterOutgoingWidget->setChecked(m_bShowOutgoing);
	m_pSaveLog = new QPushButton( filterBox, "SaveLogButton" );
	m_pSaveLog->setText("Save log to file.");

    connect(m_pFilterIncomingWidget, SIGNAL(clicked()), this, SLOT(adjustFilters()));
    connect(m_pFilterOutgoingWidget, SIGNAL(clicked()), this, SLOT(adjustFilters()));
	connect( m_pSaveLog, SIGNAL(clicked()), SLOT( saveLog() ) );


    // Set initial log capacity
    setLogCapacity(m_nCapacity);

    m_pFilterIncomingWidget->setChecked(true);
    m_pFilterOutgoingWidget->setChecked(true);

    m_bShowIncoming = true;
    m_bShowOutgoing = true;

    // A little message to start us off
    addLogEntry(0, UTF8("knateon started."));
}


void NetworkWindow::setLogCapacity(int entries)
{
    m_nCapacity = entries;
    m_pLogWidget->setMaxLogLines(m_nCapacity);
}


void NetworkWindow::addMessage(const QString &msg)
{
    // [datetime] msg\n
    QString myMsg("(");
    myMsg+= QDateTime::currentDateTime().toString(QString("yyyy-MM-dd hh:mm:ss")) + ") " + msg;
    m_pLogWidget->append(myMsg);
}


void NetworkWindow::addLogEntry(int priority, const QString &msg)
{
	Q_UNUSED( priority );
	
    addMessage(msg);
}


void NetworkWindow::addIncomingServerMessage(const QString &msg)
{
    // Filter if neccessary
    if(m_bShowIncoming)
    {
        // We're going to have to strip <> tags.
        QString ourMsg= msg;
        ourMsg.replace(QChar('<'), QString("&lt;"));
        ourMsg.replace(QChar('>'), QString("&gt;"));
        ourMsg.prepend(QString("<-- "));

        // Some incoming messages (mime-like for example) have extra \n's
        QChar endch= ourMsg.at(ourMsg.length() - 1);
        while(endch.latin1() == '\n' || endch.latin1() == '\r')
        {
            ourMsg.truncate(ourMsg.length() - 1);
            endch= ourMsg.at(ourMsg.length() - 1);
        }
        addMessage(ourMsg);
    }                            // End if (m_pShowIncoming)
}


void NetworkWindow::addOutgoingServerMessage(const QString &msg)
{
    // Filter if neccessary
    if(m_bShowOutgoing)
    {
        // We're going to have to strip <> tags.
        QString ourMsg= msg;
        ourMsg.replace(QChar('<'), QString("&lt;"));
        ourMsg.replace(QChar('>'), QString("&gt;"));
        ourMsg.prepend(QString("--> "));

        // Outgoing messages tend to have extra \n on them (we must strip them)
        QChar endch= ourMsg.at(ourMsg.length() - 1);
        while(endch.latin1() == '\n' || endch.latin1() == '\r')
        {
            ourMsg.truncate(ourMsg.length() - 1);
            endch= ourMsg.at(ourMsg.length() - 1);
        }

        addMessage(ourMsg);
    }                            // End if(m_bShowOutgoing)
}


void NetworkWindow::adjustFilters()
{
    m_bShowIncoming= m_pFilterIncomingWidget->isChecked();
    m_bShowOutgoing= m_pFilterOutgoingWidget->isChecked();
}

void NetworkWindow::saveLog()
{
	QString sFileName = QFileDialog::getSaveFileName( QDir::homeDirPath()
		+ "/" 
		+ QDateTime::currentDateTime().toString(QString("yyyy-MM-dd")) 
		+ ".txt",
		"Text (*.txt)",
		this,
		"save file dialog",
		"Choose a filename to save under" );
	
	if ( sFileName == QString::null )
		return;
	
	QFile file( sFileName );
	if ( file.open( IO_WriteOnly ) ) {
		QTextStream stream( &file );
		stream <<  m_pLogWidget->text();
		file.close();
	}
	KMessageBox::information( this, sFileName + UTF8(" 로 저장 했습니다."), UTF8("로그 저장") );	
}


#include "networkwindow.moc"
