/* This file is part of the KDE project
   Copyright (C)  2001,2002 Montel Laurent <lmontel@mandrakesoft.com>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include "KWEditPersonnalExpression.h"
#include "KWView.h"

#include <tdelocale.h>
#include <klineeditdlg.h>
#include <kdebug.h>
#include <kstandarddirs.h>

#include <tqfile.h>
#include <tqpushbutton.h>
#include <tqcombobox.h>
#include <tqlineedit.h>
#include <tqlabel.h>
#include <tqlayout.h>

KWEditPersonnalExpression::KWEditPersonnalExpression( TQWidget *parent, const char *name )
    : KDialogBase( parent, name , true, i18n("Edit Personal Expression"), Ok|Cancel, Ok, true )
{
    resize( 412, 339 );
    TQWidget *page = new TQWidget( this );
    setMainWidget(page);
    TQGridLayout* form1Layout = new TQGridLayout( page, 1, 1, 0, KDialog::spacingHint(), "form1Layout");

    TQHBoxLayout *horlayout1 = new TQHBoxLayout( 0, 0, KDialog::spacingHint(), "horlayout1");

    TQLabel *groupnameLabel = new TQLabel(i18n("Group name:"), page, "groupnameLabel" );
    horlayout1->addWidget( groupnameLabel );

    m_groupLineEdit = new TQLineEdit( page, "groupLineEdit" );
    horlayout1->addWidget( m_groupLineEdit );

    form1Layout->addLayout( horlayout1, 0, 1 );

    TQGroupBox *expressionGroupBox = new TQGroupBox( page, "expressionGroupBox" );
    expressionGroupBox->setSizePolicy( TQSizePolicy( (TQSizePolicy::SizeType)5, (TQSizePolicy::SizeType)5, 1, 0, expressionGroupBox->sizePolicy().hasHeightForWidth() ) );
    expressionGroupBox->setTitle( i18n( "Expressions" ) );
    expressionGroupBox->setColumnLayout(0, TQt::Vertical );
    expressionGroupBox->layout()->setSpacing( KDialog::spacingHint() );
    expressionGroupBox->layout()->setMargin( KDialog::marginHint() );
    TQVBoxLayout *expressionGroupBoxLayout = new TQVBoxLayout( expressionGroupBox->layout() );
    expressionGroupBoxLayout->setAlignment( TQt::AlignTop );

    m_ExpressionsList = new TQListBox( expressionGroupBox, "listOfExpressions" );
    m_ExpressionsList->setSizePolicy( TQSizePolicy( (TQSizePolicy::SizeType)7, (TQSizePolicy::SizeType)7, 1, 0, m_ExpressionsList->sizePolicy().hasHeightForWidth() ) );
    expressionGroupBoxLayout->addWidget( m_ExpressionsList );

    m_expressionLineEdit = new TQLineEdit( expressionGroupBox, "expressionLineEdit" );
    expressionGroupBoxLayout->addWidget( m_expressionLineEdit );

    TQHBoxLayout *horlayout2 = new TQHBoxLayout( 0, 0, KDialog::spacingHint(), "horlayout2");
    TQSpacerItem* spacer = new TQSpacerItem( 0, 0, TQSizePolicy::Expanding, TQSizePolicy::Minimum );
    horlayout2->addItem( spacer );

    m_addExpression = new TQPushButton( i18n("&New"), expressionGroupBox, "m_addExpression" );
    horlayout2->addWidget( m_addExpression );

    m_delExpression = new TQPushButton( i18n("&Delete"), expressionGroupBox, "m_delExpression" );
    horlayout2->addWidget( m_delExpression );
    expressionGroupBoxLayout->addLayout( horlayout2 );

    form1Layout->addWidget( expressionGroupBox, 1, 1 );

    TQVBoxLayout *vertlayout = new TQVBoxLayout( 0, 0, KDialog::spacingHint(), "vertlayout");

    m_groupList = new TQListBox( page, "groupList" );
    m_groupList->insertItem( "group1"  );
    m_groupList->setMaximumSize( TQSize( 200, 32767 ) );
    vertlayout->addWidget( m_groupList );

    TQHBoxLayout *horlayout3 = new TQHBoxLayout( 0, 0, KDialog::spacingHint(), "horlayout3");

    m_addGroup = new TQPushButton( i18n("New"), page, "m_addGroup" );
    horlayout3->addWidget( m_addGroup );

    m_delGroup = new TQPushButton(i18n("Delete"), page, "m_delGroup" );
    horlayout3->addWidget( m_delGroup );
    vertlayout->addLayout( horlayout3 );

    form1Layout->addMultiCellLayout( vertlayout, 0, 1, 0, 0 );

    loadFile();
    if(listExpression.count() == 0)
        slotAddGroup();
    else
        initGroupList();

    connect(m_groupList,TQ_SIGNAL(selectionChanged()), this,TQ_SLOT(slotGroupSelected()));
    connect(m_ExpressionsList,TQ_SIGNAL(selectionChanged()), this,TQ_SLOT(slotExpressionSelected()));
    if(m_groupList->count() > 0)  m_groupList->setSelected(0, true);

    connect(m_groupLineEdit,TQ_SIGNAL(textChanged(const TQString&)), this,TQ_SLOT(slotUpdateGroupName(const TQString&)));
    connect(m_expressionLineEdit,TQ_SIGNAL(textChanged(const TQString&)), this,TQ_SLOT(slotUpdateExpression(const TQString&)));
    connect(m_addExpression, TQ_SIGNAL( clicked() ), this,TQ_SLOT( slotAddExpression() ));
    connect(m_delExpression, TQ_SIGNAL( clicked() ), this,TQ_SLOT( slotRemoveExpression() ));
    connect(m_addGroup, TQ_SIGNAL( clicked() ), this,TQ_SLOT( slotAddGroup()));
    connect(m_delGroup, TQ_SIGNAL( clicked() ), this,TQ_SLOT( slotRemoveGroup() ));
    updateWidget();

    setFocus();
}

void KWEditPersonnalExpression::slotExpressionSelected()
{
    m_delExpression->setEnabled(m_ExpressionsList->currentItem()!=-1);
    m_expressionLineEdit->setText(m_ExpressionsList->currentText());
}

void KWEditPersonnalExpression::slotGroupSelected()
{
    m_groupLineEdit->blockSignals(true);
    m_delExpression->setEnabled(m_groupList->currentItem()!=-1);
    m_groupLineEdit->setText(m_groupList->currentText());
    list::Iterator it= listExpression.find(m_groupList->currentText());
    TQStringList lst(it.data());
    m_ExpressionsList->blockSignals(true);
    m_ExpressionsList->clear();
    m_ExpressionsList->insertStringList(lst);
    m_ExpressionsList->blockSignals(false);
    m_delExpression->setEnabled(lst.count()>0);
    if(m_ExpressionsList->count() > 0)
        m_ExpressionsList->setSelected(0, true);
    m_groupLineEdit->blockSignals(false);
}

void KWEditPersonnalExpression::slotUpdateGroupName(const TQString &newGroupName)
{
    if ( m_groupList->currentItem()==-1 )
        return;

    m_addGroup->setEnabled( true );
    list::Iterator it= listExpression.find(m_groupList->currentText());
    TQStringList lst(it.data());
    listExpression.insert(newGroupName,lst);
    listExpression.remove(m_groupList->currentText());
    m_groupList->blockSignals(true);
    m_groupList->changeItem(newGroupName, m_groupList->currentItem());
    m_groupList->blockSignals(false);
    m_bChanged=true;
}

void KWEditPersonnalExpression::slotUpdateExpression(const TQString &newExpression)
{
    if(newExpression.isEmpty() || m_groupList->currentItem()==-1 || m_ExpressionsList->currentText().isEmpty())
        return;

    list::Iterator it= listExpression.find(m_groupList->currentText());
    TQStringList lst = it.data();
    TQStringList::Iterator it2=lst.find(m_ExpressionsList->currentText());
    lst.insert(it2,TQString(newExpression));
    lst.remove(it2);
    listExpression.replace(m_groupList->currentText(),lst);

    lst.remove(m_ExpressionsList->currentText());
    m_ExpressionsList->blockSignals(true);
    m_ExpressionsList->changeItem(newExpression, m_ExpressionsList->currentItem());
    m_ExpressionsList->blockSignals(false);
    m_bChanged=true;
}

void KWEditPersonnalExpression::loadFile()
{
    TQString file=locateLocal("data","kword/expression/perso.xml");
    init( file );
}

void KWEditPersonnalExpression::initGroupList()
{
    TQStringList lst;
    m_groupList->clear();
    list::Iterator it;
    for( it = listExpression.begin(); it != listExpression.end(); ++it )
        lst<<it.key();
    m_groupList->insertStringList(lst);
}

void KWEditPersonnalExpression::init(const TQString& filename )
{
    TQFile file( filename );
    if ( !file.open( IO_ReadOnly ) )
        return;

    kdDebug() << "KWEditPersonnalExpression::init parsing " << filename << endl;
    TQDomDocument doc;
    doc.setContent( &file );
    file.close();

    TQString group = "";
    TQStringList list;
    TQDomNode n = doc.documentElement().firstChild();
    for( ; !n.isNull(); n = n.nextSibling() )
    {
        if ( n.isElement() )
        {
            TQDomElement e = n.toElement();
            if ( e.tagName() == "Type" )
            {
                list.clear();
                group = i18n( e.namedItem( "TypeName" ).toElement().text().utf8() );

                TQDomNode n2 = e.firstChild();
                for( ; !n2.isNull(); n2 = n2.nextSibling() )
                {

                    if ( n2.isElement() )
                    {
                        TQDomElement e2 = n2.toElement();
                        if ( e2.tagName() == "Expression" )
                        {
                            TQString text = i18n( e2.namedItem( "Text" ).toElement().text().utf8() );
                            list<<text;
                        }
                    }
                }
                listExpression.insert(group,list);

                group = "";
            }
        }
    }
}

void KWEditPersonnalExpression::slotOk()
{
    if( m_bChanged)
        saveFile();
    KDialogBase::slotOk();
}

void KWEditPersonnalExpression::slotAddExpression() {
    list::Iterator it= listExpression.find(m_groupList->currentText());
    TQStringList lst(it.data());
    TQString newWord = i18n("empty");
    if ( lst.contains( newWord ))
        return;
    lst<< newWord;
    listExpression.replace(m_groupList->currentText(),lst);

    m_ExpressionsList->blockSignals(true);
    m_ExpressionsList->insertItem(newWord);
    m_ExpressionsList->clearSelection();
    m_ExpressionsList->setBottomItem (m_ExpressionsList->count() -1);
    m_ExpressionsList->blockSignals(false);
    m_ExpressionsList->setSelected(m_ExpressionsList->count() -1, true);
    m_expressionLineEdit->selectAll();
    m_expressionLineEdit->setFocus();

    updateExpression();

    m_bChanged=true;
}

void KWEditPersonnalExpression::slotRemoveExpression() {
    TQString text=m_ExpressionsList->currentText ();
    if(!text.isEmpty())
    {
        list::Iterator it= listExpression.find(m_groupList->currentText());
        TQStringList lst(it.data());
        lst.remove(text);
        listExpression.replace(m_groupList->currentText(),lst);

        m_ExpressionsList->blockSignals(true);
        m_ExpressionsList->clear();
        m_ExpressionsList->insertStringList(lst);
        m_delExpression->setEnabled(lst.count()>0);
        m_ExpressionsList->blockSignals(false);
        m_expressionLineEdit->blockSignals(true);
        m_expressionLineEdit->clear();
        m_expressionLineEdit->blockSignals(false);
        m_bChanged=true;
    }
}

void KWEditPersonnalExpression::slotAddGroup() {
    listExpression.insert(i18n("new group"),TQStringList());
    initGroupList();
    m_groupList->setCurrentItem(m_groupList->count() -1);
    updateWidget();
    m_bChanged=true;
}

void KWEditPersonnalExpression::slotRemoveGroup() {
    TQString group=m_groupList->currentText();
    if(group.isEmpty())
        return;
    listExpression.remove( group );
    m_groupList->removeItem(m_groupList->currentItem());
    updateWidget();
    m_bChanged=true;
}

void KWEditPersonnalExpression::updateWidget()
{
    bool state = listExpression.count()> 0;
    m_delGroup->setEnabled( state );
    m_addExpression->setEnabled( state );
    m_groupLineEdit->setEnabled( state );

    state =state && m_ExpressionsList->count()>0;
    m_expressionLineEdit->setEnabled( state );
    m_delExpression->setEnabled( state);

}

void KWEditPersonnalExpression::updateExpression()
{
    bool state = m_ExpressionsList->count()>0;
    m_expressionLineEdit->setEnabled( state );
    m_delExpression->setEnabled( state);
}

void KWEditPersonnalExpression::saveFile()
{
    TQDomDocument doc( "KWordExpression" );
    TQDomElement begin = doc.createElement( "KWordExpression" );
    doc.appendChild( begin );
    TQStringList lst;
    list::Iterator it;
    for( it = listExpression.begin(); it != listExpression.end(); ++it )
    {
        lst=it.data();
        if ( !lst.isEmpty() )
        {
            TQDomElement type = doc.createElement( "Type" );
            begin.appendChild( type );
            TQDomElement typeName = doc.createElement( "TypeName" );
            type.appendChild( typeName );
            typeName.appendChild( doc.createTextNode(it.key()  ) );

            for( uint i=0;i<lst.count();i++ )
            {
                TQDomElement expr = doc.createElement( "Expression" );
                type.appendChild( expr );
                TQDomElement text = doc.createElement( "Text" );
                expr.appendChild( text );
                text.appendChild( doc.createTextNode(lst[i] ) );
            }
        }
    }
    TQCString s = doc.toCString();

    TQFile file( locateLocal("data","kword/expression/perso.xml") );
    if ( !file.open( IO_WriteOnly ) )
    {
        kdDebug()<<"Error \n";
        return;
    }
    file.writeBlock(s,s.length());
    file.close();
}

#include "KWEditPersonnalExpression.moc"
