/***************************************************************************
 *   Copyright (C) 2005 by Markus Brueffer <markus@brueffer.de>            *
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 *   This program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *
 ***************************************************************************/

#include "equalizerpresetmanager.h"

#include <tqdom.h>
#include <tqfile.h>
#include <tqlayout.h>
#include <tqpushbutton.h>
#include <tqvbox.h>

#include <tdeapplication.h>
#include <kinputdialog.h>
#include <tdelistview.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <tdestandarddirs.h> //locate()

EqualizerPresetManager::EqualizerPresetManager( TQWidget *parent, const char *name )
        : KDialogBase( parent, name, true, i18n("Presets"), Ok | Cancel | Default, Ok, true )
{
    TQWidget *mainWidget = new TQWidget( this );
    setMainWidget( mainWidget );
    TQHBoxLayout *mainLayout = new TQHBoxLayout( mainWidget, 0, spacingHint() );

    m_presetsView = new TDEListView( mainWidget, "presetListView" );
    m_presetsView->addColumn( i18n( "Presets" ) );
    m_presetsView->setFullWidth( true );
    connect(m_presetsView, TQ_SIGNAL( selectionChanged() ), TQ_SLOT( updateButtonState() ));
    connect(m_presetsView, TQ_SIGNAL( doubleClicked ( TQListViewItem*, const TQPoint&, int ) ), TQ_SLOT( slotRename() ));
    mainLayout->addWidget( m_presetsView );

    TQVBoxLayout* buttonsLayout = new TQVBoxLayout( mainLayout );

    m_renameBtn = new TQPushButton( i18n("&Rename"), mainWidget, "renameBtn" );
    m_deleteBtn = new TQPushButton( i18n("&Delete"), mainWidget, "deleteBtn" );

    buttonsLayout->addWidget( m_renameBtn );
    buttonsLayout->addWidget( m_deleteBtn );

    connect(m_renameBtn, TQ_SIGNAL( clicked() ), TQ_SLOT( slotRename() ));
    connect(m_deleteBtn, TQ_SIGNAL( clicked() ), TQ_SLOT( slotDelete() ));
    connect(this, TQ_SIGNAL( defaultClicked() ), TQ_SLOT( slotDefault() ));

    TQSpacerItem* spacer = new TQSpacerItem( 20, 40, TQSizePolicy::Minimum, TQSizePolicy::Expanding );
    buttonsLayout->addItem( spacer );

    updateButtonState();

    resize( TQSize(300, 250).expandedTo(minimumSizeHint()) );
}


EqualizerPresetManager::~EqualizerPresetManager()
{
}

void
EqualizerPresetManager::setPresets(TQMap< TQString, TQValueList<int> > presets)
{
    if ( presets.empty() )
        return;

    m_presets = presets;
    m_presetsView->clear();

    TQMap< TQString, TQValueList<int> >::Iterator end = presets.end();
    for ( TQMap< TQString, TQValueList<int> >::Iterator it = presets.begin(); it != end; ++it )
        if ( it.key() != i18n( "Zero" ) && it.key() != i18n( "Manual" ) ) // Don't add 'Manual' and 'Zero'
            new TDEListViewItem( m_presetsView, it.key() );
}

TQMap< TQString, TQValueList<int> >
EqualizerPresetManager::presets()
{
    return m_presets;
}

void
EqualizerPresetManager::slotRename()
{
    bool ok;
    TQListViewItem* item = m_presetsView->selectedItem();
    const TQString title = KInputDialog::getText( i18n("Rename Equalizer Preset"),
                                                 i18n("Enter new preset name:"), item->text(0), &ok, this);

    if ( ok && item->text(0) != title ) {
        // Check if the new preset title exists
        if ( m_presets.find( title ) != m_presets.end() ) {
            int button = KMessageBox::warningYesNo( this, i18n( "A preset with the name %1 already exists. Overwrite?" ).arg( title ) );

            if ( button != KMessageBox::Yes )
                return;
        }

        m_presets[ title ] = m_presets[ item->text(0)];
        m_presets.remove( item->text(0) );
        item->setText(0, title);
    }
}

void
EqualizerPresetManager::slotDefault()
{
    int button = KMessageBox::warningYesNo( this, i18n( "All presets will be deleted and defaults will be restored. Are you sure?" ) );

    if ( button != KMessageBox::Yes )
        return;

    // Preserve the 'Manual' preset
    TQValueList<int> manualGains = m_presets[ i18n("Manual") ];

    // Delete all presets
    m_presets.clear();

    // Create predefined presets 'Zero' and 'Manual'
    TQValueList<int> zeroGains;
    zeroGains << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0;
    m_presets[ i18n("Zero") ] = zeroGains;
    m_presets[ i18n("Manual") ] = manualGains;

    // Load the default presets
    TQFile file( locate( "data", "amarok/data/equalizer_presets.xml" ) );

    TQTextStream stream( &file );
    stream.setEncoding( TQTextStream::UnicodeUTF8 );

    TQDomDocument d;

    if( !file.open( IO_ReadOnly ) || !d.setContent( stream.read() ) )
        return;

    TQDomNode n = d.namedItem( "equalizerpresets" ).namedItem("preset");

    for( ; !n.isNull();  n = n.nextSibling() )
    {
        TQDomElement e = n.toElement();
        TQString title = e.attribute( "name" );

        TQValueList<int> gains;
        gains << e.namedItem( "b0" ).toElement().text().toInt();
        gains << e.namedItem( "b1" ).toElement().text().toInt();
        gains << e.namedItem( "b2" ).toElement().text().toInt();
        gains << e.namedItem( "b3" ).toElement().text().toInt();
        gains << e.namedItem( "b4" ).toElement().text().toInt();
        gains << e.namedItem( "b5" ).toElement().text().toInt();
        gains << e.namedItem( "b6" ).toElement().text().toInt();
        gains << e.namedItem( "b7" ).toElement().text().toInt();
        gains << e.namedItem( "b8" ).toElement().text().toInt();
        gains << e.namedItem( "b9" ).toElement().text().toInt();

        m_presets[ title ] = gains;
    }

    file.close();

    // Update listview
    setPresets( m_presets );
}

void
EqualizerPresetManager::slotDelete()
{
    TQListViewItem* item = m_presetsView->selectedItem();

    m_presets.remove( item->text(0) );

    delete item;
}

void
EqualizerPresetManager::updateButtonState()
{
    bool selected = ( m_presetsView->selectedItem() != 0 );

    m_deleteBtn->setEnabled( selected );
    m_renameBtn->setEnabled( selected );
}

#include "equalizerpresetmanager.moc"
