/***************************************************************************
	parser.cpp  -  Reads *.rc files in kjöfol-config-format into a TQDict
	--------------------------------------
	Maintainer: Stefan Gehn <sgehn@gmx.net>

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

// local includes
#include "parser.h"
#include "kjprefs.h"

// system includes
#include <tqtextstream.h>
#include <tqimage.h>
#include <tqfile.h>
#include <kdebug.h>
#include <kmimemagic.h>
#include <kurl.h>

Parser::Parser() : TQDict<TQStringList>(17,false)
{
	mSkinAbout="";
	mImageCache.setAutoDelete(true);
	setAutoDelete(true);
}

void Parser::conserveMemory()
{
	mImageCache.clear();
}

void Parser::open(const TQString &file)
{
	clear();
	mImageCache.clear();
	mSkinAbout="";
	mDir=KURL(file).directory();
	TQFile f(file);
	if ( !f.exists() )
		return;
	f.open(IO_ReadOnly);

	f.at(0);
	TQTextStream stream(&f);
	while (!stream.eof())
	{
		TQString line=stream.readLine();
		line=line.simplifyWhiteSpace();
		if ((!line.length()) || line[0]=='#')
			continue;
		TQStringList *l=new TQStringList(TQStringList::split(" ", (line.lower())));
		TQString first=l->first();

 		// special handling for about-texts as the key "about" can appear multiple
		// times and thus does not fit into qdict.
 		if (first=="about")
		{
			if (!mSkinAbout.isEmpty())
				mSkinAbout+="\n";

			mSkinAbout += line.mid(6);
//			kdDebug(66666) << "found About-line, mSkinAbout is now '" << mSkinAbout << "'" << endl;
			delete l; // don't need the stringlist anymore
		}
		else
			insert(first, l);
	}
}

TQString Parser::fileItem(const TQString &i) const
{
	return dir()+'/'+i;
}

TQString Parser::dir() const
{
	return mDir;
}

Parser::ImagePixmap* Parser::getPair(const TQString &filenameOld) const
{
	// is it in there?
	ImagePixmap *pair;
	{
		pair=mImageCache.find(filenameOld);
		if (pair)
			return pair;
	}

	TQString filename=fileItem(filenameOld);

	TQImage image;

	// Determine file-format trough mimetype (no stupid .ext test)
	KMimeMagicResult * result = KMimeMagic::self()->findFileType( filename );

	if ( result->mimeType() == "image/png" )
	{
//		image = NoatunApp::readPNG(filenameNoCase(filename));
		TQImageIO iio;
		iio.setFileName( filenameNoCase(filename) );
		// forget about gamma-value, fix for broken PNGs
		iio.setGamma( 0.00000001 );
		if ( iio.read() )
		{
			image = iio.image();
			image.setAlphaBuffer(false); // we don't want/support alpha-channels
		}
		else
		{
			kdDebug(66666) << "Could not load file: " << filename.latin1() << endl;
		}
	}
	else
	{
		image = TQImage(filenameNoCase(filename));
	}

	//add to the cache
	TQPixmap pixmap;
	pixmap.convertFromImage(image, TQPixmap::AutoColor|TQPixmap::ThresholdDither|TQPixmap::AvoidDither);
	pair = new Parser::ImagePixmap;
	pair->mImage = image;
	pair->mPixmap = pixmap;
	mImageCache.insert(filenameOld, pair);
	return pair;
}

bool Parser::exist(const TQString &i) const
{
	return (bool)find(i);
}
