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

/*
  Copyright (C) 2005 Peter Simonsson <psn@linux.se>
*/

#include "emoticon.h"

#include <tqregexp.h>
#include <tqdom.h>
#include <tqfile.h>
#include <tqfontmetrics.h>

#include <kstaticdeleter.h>
#include <kstandarddirs.h>
#include <tdeversion.h>

#include "konversationapplication.h"


namespace Konversation
{

    EmotIcon* EmotIcon::s_self = 0;
    static KStaticDeleter<EmotIcon> staticEmotIconDeleter;

    EmotIcon* EmotIcon::self()
    {
        if(!s_self)
        {
            staticEmotIconDeleter.setObject(s_self, new EmotIcon());
        }

        return s_self;
    }

    EmotIcon::EmotIcon()
    {
        s_self = this;

        if(Preferences::enableEmotIcons())
        {
            changeTheme(Preferences::emotIconTheme());
        }
    }

    EmotIcon::~EmotIcon()
    {
        if(s_self == this)
        {
            staticEmotIconDeleter.setObject(s_self, 0, false);
        }
    }

    void EmotIcon::changeTheme(const TQString& themeName)
    {
        if(themeName.isEmpty() || themeName == self()->m_themeName)
        {
            return;
        }

        TQString filename = TDEGlobal::dirs()->findResource("emoticons",  themeName + "/emoticons.xml");
        self()->m_themeName = themeName;
        if(filename.isEmpty())
        {
            return;
        }

        TQFile file(filename);
        file.open(IO_ReadOnly);
        TQDomDocument doc;
        doc.setContent(&file);

        TQDomElement docElement = doc.documentElement();

        if(docElement.tagName() != "messaging-emoticon-map")
        {
            return;
        }

        self()->m_emotIconMap.clear();

        TQDomNode node = docElement.firstChild();
        TQDomElement element;
        TQDomNode stringNode;
        TQDomElement stringElement;
        TQString fileAttrib;
        TQString regExpStr;

        while(!node.isNull())
        {
            element = node.toElement();

            if(!element.isNull() && element.tagName() == "emoticon")
            {
                fileAttrib = findIcon(element.attribute("file", TQString()));
                regExpStr = "";
                stringNode = element.firstChild();

                while(!stringNode.isNull())
                {
                    stringElement = stringNode.toElement();

                    if(!stringElement.isNull() && stringElement.tagName() == "string")
                    {
                        if(regExpStr.isEmpty())
                        {
                            regExpStr = "(";
                        }
                        else
                        {
                            regExpStr += '|';
                        }

                        regExpStr += TQRegExp::escape(stringElement.text());
                    }

                    stringNode = stringNode.nextSibling();
                }

                if(!regExpStr.isEmpty() && !fileAttrib.isEmpty())
                {
                    regExpStr += ')';
                    self()->m_emotIconMap[fileAttrib] = regExpStr;
                }
            }

            node = node.nextSibling();
        }
    }

    TQString EmotIcon::filter(const TQString& txt, const TQFontMetrics& fm)
    {
        if(!Preferences::enableEmotIcons())
        {
            return txt;
        }

        TQString filteredTxt = txt;

        for(EmotIconMap::iterator it = self()->m_emotIconMap.begin(); it != self()->m_emotIconMap.end(); ++it)
        {
            TQRegExp regExp(TQString("(^|\\s)%1($|\\s)").arg(it.data()));
            filteredTxt.replace(regExp, " <img width=\"" + TQString::number(fm.height()) + "\" height=\"" + TQString::number(fm.height())
                + "\" src=\"" + it.key() + "\" alt=\"" + it.data() + "\">&nbsp;");
        }

        return filteredTxt;
    }

    TQString EmotIcon::findIcon(const TQString& filename)
    {
        //
        // This code was copied from void KopeteEmoticons::addIfPossible( const TQString& filename, TQStringList emoticons )
        //  Copyright (c) 2002      by Stefan Gehn            <metz AT gehn.net>
        //  Copyright (c) 2002      by Olivier Goffart        <ogoffart@tiscalinet.be>
        //
        TDEStandardDirs *dirs = TDEGlobal::dirs();
        TQString file = self()->m_themeName + '/' + filename;
        const char* resource = "emoticons";

        //maybe an extension was given, so try to find the exact file
        TQString pic = dirs->findResource(resource, file);

        if(pic.isEmpty())
        {
            pic = dirs->findResource(resource, file + ".mng");
        }
        if(pic.isEmpty())
        {
            pic = dirs->findResource(resource, file + ".png");
        }
        if(pic.isEmpty())
        {
            pic = dirs->findResource(resource, file + ".gif");
        }

        return pic;
    }

}
