/***************************************************************************
                          sq_storagefile.cpp  -  description
                             -------------------
    begin                : Sat Mar 3 2007
    copyright            : (C) 2007 by Baryshev Dmitry
    email                : ksquirrel.iv@gmail.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.                                   *
 *                                                                         *
 ***************************************************************************/

#include <tqfile.h>
#include <tqcstring.h>
#include <tqstring.h>

#include <kmdcodec.h>

#include "sq_storagefile.h"

void SQ_StorageFile::writeStorageFile(const TQString &path, const KURL &inpath, KURL w)
{
    SQ_StorageFile::writeStorageFileAsString(path, inpath, w.prettyURL());
}

void SQ_StorageFile::writeStorageFileAsString(const TQString &path, const KURL &inpath, TQString content)
{
    if(content.isEmpty())
        content = inpath.prettyURL();

    KMD5 md5(TQFile::encodeName(inpath.prettyURL()).data());
    TQFile file(path + TQString::fromLatin1(".") + TQString(md5.hexDigest()));

    if(file.open(IO_WriteOnly))
    {
        TQCString k = content.local8Bit();
        file.writeBlock(k, k.length());
        file.close();
    }
}

KURL SQ_StorageFile::readStorageFile(const TQString &path)
{
    TQString n = SQ_StorageFile::readStorageFileAsString(path);

    int ind = n.find('\n');

    if(ind != -1)
        n.truncate(ind);

    return KURL::fromPathOrURL(n);
}

TQString SQ_StorageFile::readStorageFileAsString(const TQString &path)
{
    TQFile file(path);
    TQString str;

    if(file.open(IO_ReadOnly))
    {
        TQByteArray ba = file.readAll();
        if(file.status() == IO_Ok)
        {
            str.append(ba);
        }
    }

    file.close();

    return str;
}
