/****************************************************************************
** ui.h extension file, included from the uic-generated form implementation.
**
** If you want to add, delete, or rename functions or slots, use
** TQt Designer to update this file, preserving your code.
**
** You should not define a constructor or destructor in this file.
** Instead, write your code in functions called init() and destroy().
** These will automatically be called by the form's constructor and
** destructor.
*****************************************************************************/

#include "amarok.h"
#include "amarokconfig.h"
#include "debug.h"
#include "contextbrowser.h"

#include <tdeapplication.h>
#include <tdefiledialog.h>
#include <tdemessagebox.h>
#include <tdenewstuff/downloaddialog.h> // tdenewstuff theme fetching
#include <tdenewstuff/engine.h>         // "
#include <tdenewstuff/knewstuff.h>      // "
#include <tdenewstuff/provider.h>       // "
#include <kstandarddirs.h>
#include <ktar.h>
#include <tdeio/netaccess.h>

#include <tqdir.h>
#include <tqfileinfo.h>
#include <tqtimer.h>


////////////////////////////////////////////////////////////////////////////////
// class AmarokThemeNewStuff
////////////////////////////////////////////////////////////////////////////////

/**
 * GHNS Customised Download implementation.
 */
class AmarokThemeNewStuff : public TDENewStuff
{
    public:
    AmarokThemeNewStuff(const TQString &type, TQWidget *parentWidget=0)
             : TDENewStuff( type, parentWidget )
    {}

    bool install( const TQString& fileName )
    {
        KTar archive( fileName );

        if ( !archive.open( IO_ReadOnly ) ) {
            KMessageBox::sorry( 0, i18n( "Could not read this package." ) );
            return false;
        }

        const TQString destination = Amarok::saveLocation( "themes/" );
        debug() << "copying to " << destination << endl;
        const KArchiveDirectory* archiveDir = archive.directory();
        archiveDir->copyTo( destination, true );

        return true;
    }

    virtual bool createUploadFile( const TQString& ) { return false; }
};


////////////////////////////////////////////////////////////////////////////////
// class Options2
////////////////////////////////////////////////////////////////////////////////

void Options2::init()
{
    updateStyleComboBox();
    uninstallPushButton->setEnabled ( styleComboBox->currentText() != "Default" );
}


// This method is basically lifted from ScriptManager::slotInstallScript()
void Options2::installPushButton_clicked()
{
    KFileDialog dia( TQString(), "*.tar *.tar.bz2 *.tar.gz|" + i18n( "Style Packages (*.tar, *.tar.bz2, *.tar.gz)" ), 0, 0, true );
    kapp->setTopWidget( &dia );
    dia.setCaption( kapp->makeStdCaption( i18n( "Select Style Package" ) ) );
    dia.setMode( KFile::File | KFile::ExistingOnly );
    if ( !dia.exec() ) return;

    KTar archive( dia.selectedURL().path() );

    if ( !archive.open( IO_ReadOnly ) ) {
        KMessageBox::sorry( 0, i18n( "Could not read this package." ) );
        return;
    }

    const TQString destination = Amarok::saveLocation( "themes/" );
    debug() << "copying to " << destination << endl;
    const KArchiveDirectory* archiveDir = archive.directory();
    archiveDir->copyTo( destination, true );

    updateStyleComboBox();
}



void Options2::retrievePushButton_clicked()
{
    // Delete TDENewStuff's configuration entries. These entries reflect which styles
    // are already installed. As we cannot yet keep them in sync after uninstalling
    // styles, we deactivate the check marks entirely.
    Amarok::config()->deleteGroup( "TDENewStuffStatus" );

    // we need this because TDENewStuffGeneric's install function isn't clever enough
    AmarokThemeNewStuff *kns = new AmarokThemeNewStuff( "amarok/themes", this );
    KNS::Engine *engine = new KNS::Engine( kns, "amarok/theme", this );
    KNS::DownloadDialog* d = new KNS::DownloadDialog( engine, this );
    d->setType( "amarok/theme" );
    // you have to do this by hand when providing your own Engine
    KNS::ProviderLoader *p = new KNS::ProviderLoader( this );
    connect( p, TQ_SIGNAL( providersLoaded(Provider::List*) ), d, TQ_SLOT( slotProviders(Provider::List *) ) );
    p->load( "amarok theme", "https://www.trinitydesktop.org/ocs/providers.xml" );

    connect( d, TQ_SIGNAL( finished() ), d, TQ_SLOT( delayedDestruct() ) );
    connect( d, TQ_SIGNAL( finished() ), this, TQ_SLOT( updateStyleComboBox() ) );

    // Due to tdelibs idiocy, KNS::DownloadDialog is /always/ non-modal. So we have to
    // ensure that closing the settings dialog before the DownloadDialog doesn't crash.
    TQTimer::singleShot( 0, d, TQ_SLOT( exec() ) );
}


void Options2::uninstallPushButton_clicked()
{
    const TQString name = styleComboBox->currentText();

    if ( name == "Default" )
        return;

    if( KMessageBox::warningContinueCancel( 0,
        i18n( "<p>Are you sure you want to uninstall the theme <strong>%1</strong>?</p>" ).arg( name ),
        i18n("Uninstall Theme"), i18n("Uninstall") ) == KMessageBox::Cancel )
        return;

    if ( name == AmarokConfig::contextBrowserStyleSheet() ) {
        AmarokConfig::setContextBrowserStyleSheet( "Default" );
        ContextBrowser::instance()->reloadStyleSheet();
    }

    KURL themeDir( KURL::fromPathOrURL( Amarok::saveLocation( "themes/" ) ) );
    themeDir.addPath( name );

    if( !TDEIO::NetAccess::del( themeDir, 0 ) ) {
        KMessageBox::sorry( 0, i18n( "<p>Could not uninstall this theme.</p>"
            "<p>You may not have sufficient permissions to delete the folder <strong>%1<strong></p>."
            ).arg( themeDir.isLocalFile() ? themeDir.path() : themeDir.url() ) );
        return;
    }

    updateStyleComboBox();
}


void Options2::styleComboBox_activated(const TQString& s)
{
    bool disable = false;
    TQDir dir( Amarok::saveLocation( "themes/" ) + s );
    if( !dir.exists() )
        disable = true;

    uninstallPushButton->setEnabled ( !disable );
}


void Options2::updateStyleComboBox()
{
    DEBUG_BLOCK

    styleComboBox->clear();

    const TQStringList styleList = kapp->dirs()->findAllResources("data","amarok/themes/*/stylesheet.css", false);
    TQStringList sortedList;
    foreach (styleList) sortedList.append(TQFileInfo( *it ).dir().dirName());
    sortedList.append( "Default" );
    sortedList.sort();
    foreach(sortedList) styleComboBox->insertItem(*it);

    styleComboBox->setCurrentItem(AmarokConfig::contextBrowserStyleSheet());
}

