/* This file is part of ksirc
   Copyright (c) 2001 Malte Starostik <malte@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

// $Id$

#include <tqclipboard.h>
#include <tqdatetime.h>
#include <tqregexp.h>
#include <tqdragobject.h>
#include <tqvaluestack.h>
#include <tqstylesheet.h>

#include <tdeapplication.h>
#include <kdebug.h>
#include <tdelocale.h>
#include <krun.h>
#include <tdepopupmenu.h>
#include <kstringhandler.h>
#include <knotifyclient.h>
#include <tdefiledialog.h>
#include <tdeio/job.h>
#include <kurldrag.h>

#include "ksopts.h"
#include "ksview.moc"
#include "ksparser.h"
#include "nickColourMaker.h"
#include "ksircprocess.h"

KSircView::KSircView(KSircProcess *proc, TQWidget *parent, const char *name)
    : KSirc::TextView(parent, name), m_proc(proc)
{
    m_acceptFiles = false;
    m_timestamps = false;
    viewport()->setAcceptDrops(true);
    clear();
    connect( this, TQ_SIGNAL( linkClicked( const TQMouseEvent *, const TQString & ) ),
             this, TQ_SLOT( anchorClicked( const TQMouseEvent *, const TQString & ) ) );

    TQPixmap background = ksopts->backgroundPixmap();
    if ( !background.isNull() )
        viewport()->setBackgroundPixmap( background );

    setLinkColor( ksopts->linkColor );
}

KSircView::~KSircView()
{
}

void KSircView::clear()
{
    m_lines = 0;
    m_timeStamps.clear();
    KSirc::TextView::clear();
}

TQString KSircView::makeTimeStamp()
{
    TQTime now = TQTime::currentTime();
    TQString timeStamp = TQString::fromLatin1( "[%1:%2:%3] " )
        .arg( TQString::number( now.hour() ).rightJustify( 2, '0' ) )
        .arg( TQString::number( now.minute() ).rightJustify( 2, '0' ) )
        .arg( TQString::number( now.second() ).rightJustify( 2, '0' ) );
    return timeStamp;
}

void KSircView::saveURL( const TQString &url )
{
	KURL kurl( url );

	KFileDialog *dlg = new KFileDialog( TQString(), TQString() /*filter*/, this /*parent*/, "filedialog" /*name*/, true /*modal*/ );

	dlg->setKeepLocation( true );

	dlg->setCaption( i18n( "Save As" ) );

	if ( !kurl.fileName().isEmpty() )
		dlg->setSelection( kurl.fileName() );

	if ( dlg->exec() ) {
		KURL destURL( dlg->selectedURL() );
		if ( destURL.isValid() ) {
			TDEIO::Job *job = TDEIO::copy( kurl, destURL );
			job->setAutoErrorHandlingEnabled( true );
		}
	}

	delete dlg;
}

TQString KSircView::addLine(const TQString &pixmap, const TQColor &color, const TQString &_text)
{
    //kdDebug(5008) << "Start Text:      " << _text << endl;

    TQString richText( "<font color=\"%1\">" );
    richText = richText.arg( color.name() );

    if ( !pixmap.isEmpty() )
        richText.prepend( TQString::fromLatin1( "<img src=\"%1\"></img>" ).arg( pixmap ) );

    TQString timeStamp = TQString::fromLatin1( "<font color=\"%1\">%2</font>" )
        .arg( ksopts->textColor.name() )
        .arg( makeTimeStamp() );
    m_timeStamps.append(timeStamp);
    if ( m_timestamps )
        richText.prepend( timeStamp );

    TQString text = TQStyleSheet::escape(_text);

    // ### a bit of a hack: turn '&lt;nick&gt; message' into
    // <span>&lt;nick&gt;<span> message' . span itself isn't supported but it
    // enforces the creation of separate item objects and hence separate
    // drawing of '<nick>' and 'message' , which is needed for BiDi users,
    // according to UV Kochavi <uv1st@yahoo.com> , to prevent output like
    // '<nick message<' , which is supposedly a bug in TQt's reordering.  The
    // same is done for [nick] and >nick< to catch queries.
    TQRegExp bidiRe( "^(&lt;\\S+&gt;)(.+)$" );
    text.replace( bidiRe, TQString::fromLatin1( "<span>\\1</span>\\2" ) );
    TQRegExp bidiRe2( "^(\\[\\S+\\])(.+)$" );
    text.replace( bidiRe2, TQString::fromLatin1( "<span>\\1</span>\\2" ) );
    TQRegExp bidiRe3( "^(&gt;\\S+&lt;)(.+)$" );
    text.replace( bidiRe3, TQString::fromLatin1( "<span>\\1</span>\\2" ) );

    TQRegExp nickCol( "~n(.+)~n" );
    nickCol.setMinimal(true);
    int pos;

    while( (pos = nickCol.search(text)) >= 0 ){
        //kdDebug(5008) << "Found nick: " << nickCol.cap(1) << endl;
        TQString newText = nickCol.cap(1);
        if( nickCol.cap(1) != m_proc->getNick()){
            TQColor col = nickColourMaker::colourMaker()->findFg(nickCol.cap(1));

            newText.prepend(TQString("<font color=\"%1\">").arg(col.name()));
            newText.append("</font>");
        }  else {
            TQColor col = ksopts->ownNickColor.name();
            if( ! col.isValid())
                nickColourMaker::colourMaker()->findFg(nickCol.cap(1));
            newText.prepend(TQString("<font color=\"%1\">").arg(col.name()));
            newText.append("</font>");
            if(ksopts->ownNickBold){
                newText.prepend("<b>");
                newText.append("</b>");
            }
            if(ksopts->ownNickUl){
                newText.prepend("<u>");
                newText.append("</u>");
            }
            if(ksopts->ownNickRev){
                newText.prepend("<r>");
                newText.append("</r>");
            }
        }
        text.replace(pos, nickCol.matchedLength(), newText);
    }

    //kdDebug(5008) << "After Text:      " << text << endl;

    KSParser parser;
    richText += parser.parse( text );

    richText += "</font>";


    //kdDebug(5008) << "Text:      " << _text << endl;


    richText = KStringHandler::tagURLs( richText );
    //kdDebug(5008) << "Rich text: " << richText << endl;

    KSirc::TextParagIterator parag = appendParag( richText );

    m_lines++;
    if ( ksopts->windowLength && m_lines > ksopts->windowLength )
    {
        while ( m_lines > ksopts->windowLength )
        {
            removeParag( firstParag() );
            m_timeStamps.remove( m_timeStamps.begin() );
            m_lines--;
        }
    }

    if (parser.beeped()) {
        KNotifyClient::event(winId(), TQString::fromLatin1("BeepReceived"),
                        i18n("Beep Received"));
    }

    TQString logText = parag.plainText();
    // append timestamp if it's not already there
    if ( ! m_timestamps )
        logText.prepend( makeTimeStamp() );

    return logText + '\n';
}

void KSircView::addRichText(const TQString &_text)
{
    //kdDebug(5008) << "Start Text:      " << _text << endl;

    TQString text = _text;

    TQRegExp re("^(<font color=\"[^\"]+\">\\[[0-9:]+\\] </font>)");
    TQString timeStamp;

    if(re.search(text) >= 0){
        timeStamp = re.cap(1);
    }
    else {
	timeStamp = TQString::fromLatin1( "<font color=\"%1\">%2</font>" )
	    .arg( ksopts->textColor.name() )
	    .arg( makeTimeStamp() );
	if ( m_timestamps )
	    text.prepend( timeStamp );
    }
    m_timeStamps.append(timeStamp);

    KSirc::TextParagIterator parag = appendParag( text );

    m_lines++;
    if ( ksopts->windowLength && m_lines > ksopts->windowLength )
    {
        while ( m_lines > ksopts->windowLength )
        {
            removeParag( firstParag() );
            m_timeStamps.remove( m_timeStamps.begin() );
            m_lines--;
        }
    }

}

void KSircView::enableTimeStamps(bool enable)
{
    if(enable == m_timestamps)
        return;
    setUpdatesEnabled( false );
    m_timestamps = enable;
    KSirc::TextParagIterator paragIt = firstParag();
    TQStringList::ConstIterator timeStampIt = m_timeStamps.begin();
    for (; !paragIt.atEnd(); ++paragIt, ++timeStampIt )
    {
        TQString text = paragIt.richText();
        if ( enable )
            text.prepend( *timeStampIt );
        else
            text.remove( 0, (*timeStampIt).length() );
        paragIt.setRichText( text );
    }
    setUpdatesEnabled( true );
    updateContents();
}

void KSircView::anchorClicked(const TQMouseEvent *ev, const TQString &url)
{
    if ( (ev->button() & TQt::LeftButton) && (ev->state() & ShiftButton ) )
		saveURL( url );
	else if ( (ev->button() & TQt::LeftButton) || (ev->button() & TQt::MidButton) )
    {
        openBrowser( url );
    }
    else if ( ev->button() & TQt::RightButton )
    {
        static const int openURLID = 0;
        static const int copyLinkLocationID = 1;

        // Adding a nice contextmenu
        TDEPopupMenu* menu = new TDEPopupMenu( this );
        menu->insertTitle( i18n( "URL" ) );
        menu->insertItem( i18n("Open URL"), openURLID );
        menu->insertItem( i18n("Copy Link Address"), copyLinkLocationID );
        switch( menu->exec( ( ev->globalPos() ) ) )
        {
        case openURLID :
            openBrowser( url );
            break;
        case copyLinkLocationID :
            copyLinkToClipboard( url );
            break;
        default:
            break;
        }
        delete menu;
    }
}

void KSircView::openBrowser(const TQString &url )
{
    (void) new KRun( KURL( url.startsWith("www") ? TQString::fromLatin1("http://") + url : url));
}

void KSircView::copyLinkToClipboard( const TQString &url )
{
    TQApplication::clipboard()->setText( url, TQClipboard::Clipboard );
}

TQColor KSircView::ircColor(int code)
{
    if (code >= 0 && code < 16)
        return ksopts->ircColors[code];
    return TQColor();
}

void KSircView::contentsDragEnterEvent(TQDragEnterEvent* event)
{
    event->accept((TQTextDrag::canDecode(event) ||
                   (m_acceptFiles && KURLDrag::canDecode(event))) &&
                  (!event->source() || event->source() != viewport()));
}

void KSircView::contentsDragMoveEvent(TQDragMoveEvent* event)
{
    event->accept(!event->source() || event->source() != viewport());
}

void KSircView::contentsDropEvent(TQDropEvent* event)
{
    TQStringList urls;
    TQString text;

    if (m_acceptFiles && KURLDrag::decodeLocalFiles(event, urls))
        emit urlsDropped(urls);
    else if (TQTextDrag::decode(event, text))
        emit textDropped(text);
}
