/*
  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.
*/

/*
  Shows the content of a log file
  begin:     Fri Dec 5 2003
  copyright: (C) 2003 by Dario Abatianni
  email:     eisfuchs@tigress.com
*/

#include "logfilereader.h"
#include "konversationapplication.h"
#include "ircview.h"
#include "ircviewbox.h"

#include <tqlayout.h>
#include <tqfile.h>
#include <tqtextstream.h>
#include <tqdockarea.h>
#include <tqpushbutton.h>
#include <tqlabel.h>
#include <tqregexp.h>
#include <tqspinbox.h>
#include <tqstylesheet.h>
#include <tqwhatsthis.h>

#include <kdialog.h>
#include <tdetoolbar.h>
#include <tdemessagebox.h>
#include <tdefiledialog.h>
#include <tdelocale.h>
#include <kdebug.h>
#include <tdeio/jobclasses.h>


LogfileReader::LogfileReader(TQWidget* parent, const TQString& log) : ChatWindow(parent)
{
    setType(ChatWindow::LogFileReader);

    fileName = log;
    TQDockArea* toolBarDock = new TQDockArea(TQt::Horizontal,TQDockArea::Normal,this,"logfile_toolbar_dock");
    toolBar = new TDEToolBar(toolBarDock,"logfile_toolbar",true,true);

    toolBar->insertButton("document-save-as",0,TQ_SIGNAL(clicked()),this,TQ_SLOT(saveLog()),true,i18n("Save As..."));

    new TQLabel(i18n("Show last:"),toolBar,"logfile_size_label");
    sizeSpin = new TQSpinBox(10,1000,10,toolBar,"logfile_size_spinbox");
    TQWhatsThis::add(sizeSpin, i18n("Use this box to set the maximum size of the log file. This setting does not take effect until you restart Konversation. Each log file may have a separate setting."));
    sizeSpin->setValue(Preferences::logfileBufferSize());
    sizeSpin->setSuffix(i18n(" KB"));
    sizeSpin->installEventFilter(this);

    toolBar->insertButton("reload",0,TQ_SIGNAL(clicked()),this,TQ_SLOT(updateView()),true,i18n("Reload"));
    toolBar->insertButton("edit-delete",0,TQ_SIGNAL(clicked()),this,TQ_SLOT(clearLog()),true,i18n("Clear Logfile"));

    IRCViewBox* ircBox = new IRCViewBox(this, 0);
    setTextView(ircBox->ircView());
    TQWhatsThis::add(getTextView(), i18n("The messages in the log file are displayed here. The oldest messages are at the top and the most recent are at the bottom."));

    updateView();
    resize(Preferences::logfileReaderSize());
    ircBox->ircView()->setFocusPolicy(TQWidget::StrongFocus);
    setFocusPolicy(TQWidget::StrongFocus);
    setFocusProxy(ircBox->ircView());

    connect(getTextView(), TQ_SIGNAL(gotFocus()), getTextView(), TQ_SLOT(setFocus()));
}

LogfileReader::~LogfileReader()
{
    Preferences::setLogfileReaderSize(size());
    Preferences::setLogfileBufferSize(sizeSpin->value());

    delete toolBar;
}

bool LogfileReader::eventFilter(TQObject* /* watched */, TQEvent* e)
{
    if (e->type() == TQEvent::KeyPress)
    {
        TQKeyEvent* ke = static_cast<TQKeyEvent*>(e);

        if (ke->key() == TQt::Key_Return || ke->key() == TQt::Key_Enter)
        {
            updateView();

            return true;
        }
        else
            return false;
    }

    return false;
}

void LogfileReader::updateView()
{
    // get maximum size of logfile to display
    unsigned long pos=sizeSpin->value()*1024;
    getTextView()->clear();

    TQFile file(fileName);

    if(file.open(IO_ReadOnly))
    {
        TQTextStream stream(&file);
        stream.setEncoding(TQTextStream::UnicodeUTF8);

        // Set file pointer to <pos> bytes from the end
        if(stream.device()->size()>pos)
            stream.device()->at(stream.device()->size()-pos);
        // Skip first line, since it may be incomplete
        stream.readLine();
        TQString str;

        while(!stream.eof())
        {
            str = TQStyleSheet::escape(stream.readLine());
            getTextView()->appendRaw(str, true);
        }

        stream.unsetDevice();
        file.close();
    }
}

void LogfileReader::clearLog()
{
    if(KMessageBox::warningContinueCancel(this,
        i18n("Do you really want to permanently discard all log information of this file?"),
        i18n("Clear Logfile"),
        KStdGuiItem::del(),
        "ClearLogfileQuestion")==KMessageBox::Continue)
    {
        TQFile::remove(fileName);
        updateView();
    }
}

void LogfileReader::saveLog()
{
    KMessageBox::information(this,
        i18n("Note: By saving the logfile you will save all data in the file, not only the part you can see in this viewer."),
        i18n("Save Logfile"),
        "SaveLogfileNote");

    TQString destination=KFileDialog::getSaveFileName(fileName,
        TQString(),
        this,
        i18n("Choose Destination Folder"));
    if(!destination.isEmpty())
    {
        // replace # with %25 to make it URL conforming
        TDEIO::Job* job=TDEIO::copy(KURL(fileName.replace("#","%23")),
            KURL(destination),
            true);

        connect(job,TQ_SIGNAL(result(TDEIO::Job*)),this,TQ_SLOT(copyResult(TDEIO::Job*)));
    }
}

void LogfileReader::copyResult(TDEIO::Job* job)
{
    if(job->error()) job->showErrorDialog(this);

    job->deleteLater();
}

void LogfileReader::closeLog()
{
    delete this;
}

void LogfileReader::childAdjustFocus()
{
  getTextView()->setFocus();
}

int LogfileReader::margin() { return KDialog::marginHint(); }
int LogfileReader::spacing() { return KDialog::spacingHint(); }
bool LogfileReader::searchView() { return true; }

#include "logfilereader.moc"
