/**********************************************************************

	--- Dlgedit generated file ---

	File: EditFile.cpp
	Last generated: Thu Aug 7 11:28:21 1997

 *********************************************************************/

#include "EditFile.h"
#include <qfile.h>
#include <qfiledlg.h>
#include <iostream.h>
// KDE
#include <kmsgbox.h>
#include "ircapp.h"

#define Inherited EditFileData

EditFile::EditFile
(
	QWidget* parent,
	const char* name
)
	:
	Inherited( parent, name )
{
    fileName = "";
}

void EditFile::setFileName ( QString nm )
{
    if (nm != "")
    {
        if (QFile::exists(IrcApp::GetFile(nm)))
        {
            fileName = nm;
            slotReload();
        }
        else
        {
            KMsgBox::message(0, "Bad file name", "The file name you have entered is not valid.\n"
                             "Try again.", KMsgBox::EXCLAMATION);
            warning("Bad file name");
        }
        
    }
}


EditFile::~EditFile()
{
    
}

void EditFile::slotClear()
{
    fileMultiLineEdit->setText("");
}

void EditFile::slotSave()
{
    QFile file(IrcApp::GetFile(fileName));
    QDir d(IrcApp::GetFile(fileName));
    if (d.exists())
        return;
    if (!file.open(IO_WriteOnly))
        return;
    
    QString fileBuffer = fileMultiLineEdit->text();
    //cout << "fileBuffer = " << fileBuffer.data() << endl;
    file.writeBlock(fileBuffer, fileBuffer.size());
}

void EditFile::slotBrowse()
{
    QString f;
    QString fn = IrcApp::GetFile(fn);
    int i = fn.findRev("/", fn.size()-1);
    if (i == -1)
        f = QFileDialog::getOpenFileName(Settings::fileDir, 0, this);
    else
    {
        QString fileDir = fn.left(i);
        f = QFileDialog::getOpenFileName(fileDir, 0, this);
    }
    
    if (!f.isEmpty())
    {
        setFileName(f);
    }
        
}

void EditFile::slotFileNameChanged()
{
    setFileName(fileNameEdit->text());
}

void EditFile::slotReload()
{
    
    fileNameEdit->setText(fileName); // just in case we have gotten lost
    QFile file(IrcApp::GetFile(fileName));
    QDir d(IrcApp::GetFile(fileName));
    if (d.exists())
        return;
    QString fileBuffer;
    
    if (!file.open(IO_ReadOnly))
    {
        fileBuffer = "";
        
    }
    else
    {  
        char buff[512];
        while (!file.atEnd())
        {
            bzero(buff, 512);
            file.readBlock(buff, 511);
            // cout << "buff= " << buff << endl;
            fileBuffer+=buff;
        }
        file.close();
    }
    fileMultiLineEdit->setText(fileBuffer);
     
}

#include "EditFile.moc"
#include "EditFileData.moc"
