/*
    appearanceconfig.cpp  -  Kopete Look Feel Config

    Kopete    (c) 2002-2009 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * 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 "emoticonseditdialog.h"
#include "emoticonseditwidget.h"

#include "kopeteglobal.h"
#include "kopeteprefs.h"
#include "kopeteemoticons.h"

#include <tdelocale.h>
#include <tdelistview.h>
#include <kstandarddirs.h>
#include <tdefiledialog.h>
#include <tdeio/job.h>
#include <tqpixmap.h>
#include <tqheader.h>
#include <tqlayout.h>
#include <tqlabel.h>


EditDialog::EditDialog(TQWidget *parent, const char* name)
    : KDialogBase(parent, name, true, i18n(name), Ok|Cancel, Ok, true)
{
    setupDlg();
}

EditDialog::EditDialog(TQWidget *parent, const char* name, TQPixmap emot, TQString text, TQString file)
    : KDialogBase(parent, name, true, i18n(name), Ok|Cancel, Ok, true)
{
    setupDlg();
    leText->setText(text);
    btnIcon->setPixmap(emot);
    emoticon = file;
}

void EditDialog::setupDlg()
{
    wdg = new TQWidget(this);
    TQVBoxLayout *vl = new TQVBoxLayout(wdg, 11, 6);
    TQHBoxLayout *hb = new TQHBoxLayout(wdg, 0, 6);
    leText = new KLineEdit(wdg);
    btnIcon = new KPushButton(wdg);
    btnIcon->setFixedSize(TQSize(64, 64));

    vl->addWidget(new TQLabel(i18n("Insert the string for the emoticon\nseparated by space if you want multiple strings"), wdg));
    hb->addWidget(btnIcon);
    hb->addWidget(leText);
    vl->addLayout(hb);
    setMainWidget(wdg);
    connect(btnIcon, TQ_SIGNAL(clicked()), this, TQ_SLOT(btnIconClicked()));
}

void EditDialog::btnIconClicked()
{
    KURL url =  KFileDialog::getImageOpenURL();

    if(!url.isLocalFile())
        return;

    emoticon = url.path();

    if(emoticon.isEmpty())
        return;

    btnIcon->setPixmap(TQPixmap(emoticon));
}

EmoticonsEditDialog::EmoticonsEditDialog(TQWidget *parent, TQString theme, const char* name)
    : KDialogBase(parent, name, true, i18n("Emoticons Editor"), Ok|Cancel, Ok, true)
{
    themeName = theme;

    mMainWidget = new EmoticonsEditWidget(this, "EmoticonsEditDialog::mMainWidget");
    setMainWidget(mMainWidget);
    resize(TQSize(450, 350));
    mMainWidget->btnAdd->setGuiItem(KStdGuiItem::add());
    mMainWidget->btnEdit->setText(i18n("Edit..."));
    mMainWidget->btnRemove->setGuiItem(KStdGuiItem::remove());


    mMainWidget->klvEmoticons->addColumn("Emoticon");
    mMainWidget->klvEmoticons->addColumn("Text");
    mMainWidget->klvEmoticons->addColumn("File", 0);
    mMainWidget->klvEmoticons->header()->hide();
    Kopete::Emoticons emoticons( theme );
    TQMap<TQString, TQStringList> smileys = emoticons.emoticonAndPicList();


    for(TQMap<TQString, TQStringList>::Iterator it = smileys.begin(); it != smileys.end(); ++it )
    {
        TDEListViewItem *itm = new TDEListViewItem(mMainWidget->klvEmoticons);
        itm->setPixmap(0, TQPixmap(it.key()));
        itm->setText(2, TQFileInfo(it.key()).baseName());
        TQString text = *it.data().at(0);
        for(uint i = 1; i < it.data().size(); i++) {
            text += " " + *it.data().at(i);
        }
        itm->setText(1, text);
    }

    TQFile *fp = new TQFile(TDEGlobal::dirs()->saveLocation( "emoticons",  themeName, false ) +  "/emoticons.xml");

    if( !fp->exists() ) {
        kdWarning() << "EmoticonsEditDialog::EmoticonsEditDialog() " << fp->name() << " doesn't exist!" << endl;
        return;
    }

    if(!fp->open( IO_ReadOnly )) {
        kdWarning() << "EmoticonsEditDialog::EmoticonsEditDialog() " << fp->name() << " can't open ReadOnly!" << endl;
        return;
    }

    if(!themeXml.setContent(fp)) {
        kdWarning() << "EmoticonsEditDialog::EmoticonsEditDialog() " << fp->name() << " can't copy to xml!" << endl;
        fp->close();
        return;
    }

    fp->close();

    mMainWidget->klvEmoticons->setColumnWidth(0, TQListView::Maximum);
    mMainWidget->klvEmoticons->setColumnWidth(1, TQListView::Maximum);

    connect(this, TQ_SIGNAL(okClicked()), this, TQ_SLOT(slotOkClicked()));
    connect(mMainWidget->btnAdd, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotAddClicked()));
    connect(mMainWidget->btnEdit, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotEditClicked()));
    connect(mMainWidget->btnRemove, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotRemoveClicked()));
}

void EmoticonsEditDialog::slotOkClicked()
{
    TQFile *fp = new TQFile(TDEGlobal::dirs()->saveLocation( "emoticons",  themeName, false ) +  "/emoticons.xml");

    if( !fp->exists() ) {
        kdWarning() << "EmoticonsEditDialog::slotOkClicked() " << fp->name() << " doesn't exist!" << endl;
        return;
    }

    if(!fp->open( IO_WriteOnly )) {
        kdWarning() << "EmoticonsEditDialog::slotOkClicked() " << fp->name() << " can't open WriteOnly!" << endl;
        return;
    }

    TQTextStream emoStream(fp);
    emoStream << themeXml.toString(4);
    fp->close();
}

void EmoticonsEditDialog::slotAddClicked()
{
    EditDialog *dlg = new EditDialog(this, "Add emoticon");

    if(dlg->exec() == TQDialog::Rejected)
        return;

    if(dlg->getText().isEmpty() || !dlg->getEmoticon())
        return;

    addEmoticon(dlg->getEmoticon(), dlg->getText(), true);


    delete dlg;
}

void EmoticonsEditDialog::slotEditClicked()
{
    if(!mMainWidget->klvEmoticons->selectedItem())
        return;

    dlg = new EditDialog(this, "Edit emoticon", *mMainWidget->klvEmoticons->selectedItem()->pixmap(0), mMainWidget->klvEmoticons->selectedItem()->text(1),  mMainWidget->klvEmoticons->selectedItem()->text(2));

    if(dlg->exec() == TQDialog::Rejected)
        return;

    if(dlg->getText().isEmpty() || !dlg->getEmoticon())
        return;

    bool copy;
    TQString emo = dlg->getEmoticon();
    if(mMainWidget->klvEmoticons->selectedItem()->text(2) != dlg->getEmoticon()) {
        copy = true;
    } else {
        copy = false;
        TQString f = mMainWidget->klvEmoticons->selectedItem()->text(2);

        TDEStandardDirs *dir = TDEGlobal::dirs();
        emo = dir->findResource( "emoticons", themeName + TQString::fromLatin1( "/" ) + f );

        if( emo.isNull() )
            emo = dir->findResource( "emoticons", themeName + TQString::fromLatin1( "/" ) + f + TQString::fromLatin1( ".mng" ) );
        if ( emo.isNull() )
            emo = dir->findResource( "emoticons", themeName + TQString::fromLatin1( "/" ) + f + TQString::fromLatin1( ".png" ) );
        if ( emo.isNull() )
            emo = dir->findResource( "emoticons", themeName + TQString::fromLatin1( "/" ) + f + TQString::fromLatin1( ".gif" ) );
        if ( emo.isNull() )
            return;
    }

    removeEmoticon(mMainWidget->klvEmoticons->selectedItem()->text(2));
    addEmoticon(emo, dlg->getText(), copy);

    delete dlg;
}

void EmoticonsEditDialog::slotRemoveClicked()
{
    if(!mMainWidget->klvEmoticons->selectedItem())
        return;

    removeEmoticon(mMainWidget->klvEmoticons->selectedItem()->text(2));
}

void EmoticonsEditDialog::addEmoticon(TQString emo, TQString text, bool copy)
{
    if(copy)
        TDEIO::copy(emo, TDEGlobal::dirs()->saveLocation( "emoticons",  themeName, false ));

    TDEListViewItem *itm = new TDEListViewItem(mMainWidget->klvEmoticons);
    itm->setPixmap(0, TQPixmap(emo));
    itm->setText(1, text);
    itm->setText(2, TQFileInfo(emo).baseName());

    TQDomNode lc = themeXml.lastChild();
    if(lc.isNull())
        return;

    TQDomElement emoticon = themeXml.createElement("emoticon");
    emoticon.setAttribute("file", TQFileInfo(emo).baseName());
    lc.appendChild(emoticon);
    TQStringList splitted = TQStringList::split(" ", text);
    TQStringList::const_iterator constIterator;
    for(constIterator = splitted.begin(); constIterator != splitted.end(); constIterator++)
    {
        TQDomElement emotext = themeXml.createElement("string");
        TQDomText txt = themeXml.createTextNode((*constIterator).stripWhiteSpace());
        emotext.appendChild(txt);
        emoticon.appendChild(emotext);
    }
}

void EmoticonsEditDialog::removeEmoticon(TQString emo)
{
    TQDomNode lc = themeXml.lastChild();
    if(lc.isNull())
        return;

    TQDomNodeList nl = lc.childNodes();

    for(uint i = 0; i < nl.length(); i++) {
        TQDomElement de = nl.item(i).toElement();
        if(!de.isNull() && de.tagName() == "emoticon" && de.attribute("file") == emo) {
            lc.removeChild(de);
            delete mMainWidget->klvEmoticons->selectedItem();
            return;
        }
    }
}

#include "emoticonseditdialog.moc"
