
#include "cdopener.h"
#include "cdmanager.h"
#include "tagengine.h"
#include "configuration.h"
#include "ripperpluginloader.h"
#include "combobutton.h"

#include <tdelistview.h>
#include <tdelocale.h>
#include <kiconloader.h>
#include <kpushbutton.h>
#include <klineedit.h>
#include <kcombobox.h>
#include <knuminput.h>
#include <ktextedit.h>
#include <tdefiledialog.h>
#include <tdemessagebox.h>

#include <tqlayout.h>
#include <tqlabel.h>
#include <tqgroupbox.h>
#include <tqdatetime.h>
#include <tqcolor.h>
#include <tqdir.h>
#include <tqfile.h>

// ### soundkonverter 0.4: implement cd info text

CDOpener::CDOpener( Config* _config, CDManager* _cdManager, TagEngine* _tagEngine, const TQString& _device, TQWidget* parent, const char* name, /*Mode default_mode, const TQString& default_text,*/ bool modal, WFlags f )
    : KDialog( parent, name, modal, f )
{
    cdManager = _cdManager;
    tagEngine = _tagEngine;
    config = _config;

    // create an icon loader object for loading icons
    TDEIconLoader* iconLoader = new TDEIconLoader();

    // let the dialog look nice
    setCaption( i18n("Add CD tracks") );
    setIcon( iconLoader->loadIcon("media-optical-cdaudio-unmounted",TDEIcon::Small) );

    // the grid for all widgets in the dialog
    TQGridLayout* gridLayout = new TQGridLayout( this, 1, 1, 11, 6, "gridLayout" );

    // the grid for the artist and album input
    TQGridLayout* topGridLayout = new TQGridLayout( this, 1, 1, 0, 6, "topGridLayout" );
    gridLayout->addLayout( topGridLayout, 0, 0 );

    // set up the first row at the top
    TQLabel* lArtistLabel = new TQLabel( i18n("Artist:"), this, "lArtistLabel" );
    topGridLayout->addWidget( lArtistLabel, 0, 0 );
    cArtist = new KComboBox( true, this, "cArtist" );
    topGridLayout->addWidget( cArtist, 0, 1 );
    cArtist->setMinimumWidth( 200 );
    cArtist->insertItem( i18n("Various Artists") );
    cArtist->setCurrentText( "" );
    connect( cArtist, TQ_SIGNAL(textChanged(const TQString&)),
               this, TQ_SLOT(artistChanged(const TQString&))
             );
    // add a horizontal box layout for the composer
    TQHBoxLayout* artistBox = new TQHBoxLayout( -1, "artistBox" );
    topGridLayout->addLayout( artistBox, 0, 3 );
    // and fill it up
    TQLabel* lComposerLabel = new TQLabel( i18n("Composer:"), this, "lComposerLabel" );
    lComposerLabel->setAlignment( TQt::AlignRight | TQt::AlignVCenter );
    topGridLayout->addWidget( lComposerLabel, 0, 2 );
    cComposer = new KComboBox( true, this, "cComposer" );
    artistBox->addWidget( cComposer );
    cComposer->insertItem( i18n("Various Composer") );
    cComposer->setCurrentText( "" );
    //cComposer->setSizePolicy( TQSizePolicy::Maximum );
    connect( cComposer, TQ_SIGNAL(textChanged(const TQString&)),
               this, TQ_SLOT(composerChanged(const TQString&))
             );
    //artistBox->addStretch();
    artistBox->addSpacing( 130 );
//     pCDDB = new KPushButton( iconLoader->loadIcon("media-optical-cdaudio-unmounted",TDEIcon::Small), i18n("Request CDDB"), this, "pCDDB" );
//     topGridLayout->addWidget( pCDDB, 0, 8 );

    // set up the second row at the top
    TQLabel* lAlbumLabel = new TQLabel( i18n("Album:"), this, "lAlbumLabel" );
    topGridLayout->addWidget( lAlbumLabel, 1, 0 );
    lAlbum = new KLineEdit( this, "lAlbum" );
    topGridLayout->addWidget( lAlbum, 1, 1 );
    // add a horizontal box layout for the disc number, year and genre
    TQHBoxLayout* albumBox = new TQHBoxLayout( -1, "albumBox" );
    topGridLayout->addLayout( albumBox, 1, 3 );
    // and fill it up
    TQLabel* lDiscLabel = new TQLabel( i18n("Disc No.:"), this, "lDiscLabel" );
    lDiscLabel->setAlignment( TQt::AlignRight | TQt::AlignVCenter );
    topGridLayout->addWidget( lDiscLabel, 1, 2 );
    iDisc = new KIntSpinBox( 1, 99, 1, 1, 10, this, "iDisc" );
    albumBox->addWidget( iDisc );
    TQLabel* lYearLabel = new TQLabel( i18n("Year:"), this, "lYearLabel" );
    albumBox->addWidget( lYearLabel );
    iYear = new KIntSpinBox( 0, 99999, 1, TQDate::currentDate().year(), 10, this, "iYear" );
    albumBox->addWidget( iYear );
    TQLabel* lGenreLabel = new TQLabel( i18n("Genre:"), this, "lGenreLabel" );
    albumBox->addWidget( lGenreLabel );
    cGenre = new KComboBox( true, this, "cGenre" );
    cGenre->insertStringList( tagEngine->genreList );
    cGenre->setCurrentText( "" );
    TDECompletion* cGenreCompletion = cGenre->completionObject();
    cGenreCompletion->insertItems( tagEngine->genreList );
    cGenreCompletion->setIgnoreCase( true );
    albumBox->addWidget( cGenre );

    // generate the list view for the tracks
    trackList = new TDEListView( this, "trackList" );
    gridLayout->addWidget( trackList, 1, 0 );
    // and fill in the headers
    trackList->addColumn( i18n("Track") );
    trackList->addColumn( i18n("Artist"), 0 );
    trackList->addColumn( i18n("Composer"), 0 );
    trackList->addColumn( i18n("Title") );
    trackList->addColumn( i18n("Time") );
    trackList->setSelectionMode( TQListView::Extended );
    trackList->setAllColumnsShowFocus( true );
    trackList->setResizeMode( TQListView::LastColumn );
    connect( trackList, TQ_SIGNAL(selectionChanged()),
               this, TQ_SLOT(trackChanged())
             );
    connect( trackList, TQ_SIGNAL(doubleClicked(TQListViewItem*,const TQPoint&,int)),
               this, TQ_SLOT(addClicked())
             );
    gridLayout->setRowStretch( 1, 1 );

    // create the box at the bottom for editing the tags
    tagGroupBox = new TQGroupBox( i18n("No track selected"), this, "tagGroupBox" );
    gridLayout->addWidget( tagGroupBox, 2, 0 );
    tagGroupBox->setColumnLayout( 0, TQt::Vertical );
    tagGroupBox->layout()->setSpacing( 6 );
    tagGroupBox->layout()->setMargin( 6 );
    TQGridLayout* tagGridLayout = new TQGridLayout( tagGroupBox->layout(), 1, 1, -1, "tagGridLayout" );

    // add the up and down buttons
    pTrackUp = new KPushButton( " ", tagGroupBox, "pTrackUp" );
    pTrackUp->setPixmap( iconLoader->loadIcon("go-up",TDEIcon::Toolbar) );
    pTrackUp->setAutoRepeat( true );
    connect( pTrackUp, TQ_SIGNAL(clicked()),
               this, TQ_SLOT(trackUpPressed())
             );
    tagGridLayout->addWidget( pTrackUp, 0, 0 );
    pTrackDown = new KPushButton( " ", tagGroupBox, "pTrackDown" );
    pTrackDown->setPixmap( iconLoader->loadIcon("go-down",TDEIcon::Toolbar) );
    pTrackDown->setAutoRepeat( true );
    connect( pTrackDown, TQ_SIGNAL(clicked()),
               this, TQ_SLOT(trackDownPressed())
             );
    tagGridLayout->addWidget( pTrackDown, 1, 0 );

    // add the inputs
    // add a horizontal box layout for the title
    TQHBoxLayout* trackTitleBox = new TQHBoxLayout( -1, "trackTitleBox" );
    tagGridLayout->addLayout( trackTitleBox, 0, 2 );
    // and fill it up
    TQLabel *lTrackTitleLabel = new TQLabel( i18n("Title:"), tagGroupBox, "lTrackTitleLabel" );
    tagGridLayout->addWidget( lTrackTitleLabel, 0, 1 );
    lTrackTitle = new KLineEdit( tagGroupBox, "lTrackTitle" );
    trackTitleBox->addWidget( lTrackTitle );
    connect( lTrackTitle, TQ_SIGNAL(textChanged(const TQString&)),
               this, TQ_SLOT(trackTitleChanged(const TQString&))
             );
    pTrackTitleEdit = new KPushButton( " ", tagGroupBox, "pTrackTitleEdit" );
    pTrackTitleEdit->setPixmap( iconLoader->loadIcon("kwrite",TDEIcon::Small) );
    pTrackTitleEdit->setFixedSize( lTrackTitle->sizeHint().height(), lTrackTitle->sizeHint().height() );
    pTrackTitleEdit->hide();
    trackTitleBox->addWidget( pTrackTitleEdit );
    connect( pTrackTitleEdit, TQ_SIGNAL(clicked()),
               this, TQ_SLOT(editTrackTitleClicked())
             );
    // add a horizontal box layout for the composer
    TQHBoxLayout* trackArtistBox = new TQHBoxLayout( -1, "trackArtistBox" );
    tagGridLayout->addLayout( trackArtistBox, 1, 2 );
    // and fill it up
    TQLabel* lTrackArtistLabel = new TQLabel( i18n("Artist:"), tagGroupBox, "lTrackArtistLabel" );
    tagGridLayout->addWidget( lTrackArtistLabel, 1, 1 );
    lTrackArtist = new KLineEdit( tagGroupBox, "lTrackArtist" );
    trackArtistBox->addWidget( lTrackArtist );
    connect( lTrackArtist, TQ_SIGNAL(textChanged(const TQString&)),
               this, TQ_SLOT(trackArtistChanged(const TQString&))
             );
    pTrackArtistEdit = new KPushButton( " ", tagGroupBox, "pTrackArtistEdit" );
    pTrackArtistEdit->setPixmap( iconLoader->loadIcon("kwrite",TDEIcon::Small) );
    pTrackArtistEdit->setFixedSize( lTrackArtist->sizeHint().height(), lTrackArtist->sizeHint().height() );
    pTrackArtistEdit->hide();
    trackArtistBox->addWidget( pTrackArtistEdit );
    connect( pTrackArtistEdit, TQ_SIGNAL(clicked()),
               this, TQ_SLOT(editTrackArtistClicked())
             );
    TQLabel* lTrackComposerLabel = new TQLabel( i18n("Composer:"), tagGroupBox, "lTrackComposerLabel" );
    trackArtistBox->addWidget( lTrackComposerLabel );
    lTrackComposer = new KLineEdit( tagGroupBox, "lTrackComposer" );
    trackArtistBox->addWidget( lTrackComposer );
    connect( lTrackComposer, TQ_SIGNAL(textChanged(const TQString&)),
               this, TQ_SLOT(trackComposerChanged(const TQString&))
             );
    pTrackComposerEdit = new KPushButton( " ", tagGroupBox, "pTrackComposerEdit" );
    pTrackComposerEdit->setPixmap( iconLoader->loadIcon("kwrite",TDEIcon::Small) );
    pTrackComposerEdit->setFixedSize( lTrackComposer->sizeHint().height(), lTrackComposer->sizeHint().height() );
    pTrackComposerEdit->hide();
    trackArtistBox->addWidget( pTrackComposerEdit );
    connect( pTrackComposerEdit, TQ_SIGNAL(clicked()),
               this, TQ_SLOT(editTrackComposerClicked())
             );
    // add a horizontal box layout for the comment
    TQHBoxLayout* trackCommentBox = new TQHBoxLayout( -1, "trackCommentBox" );
    tagGridLayout->addLayout( trackCommentBox, 2, 2 );
    // and fill it up
    TQLabel* lTrackCommentLabel = new TQLabel( i18n("Comment:"), tagGroupBox, "lTrackCommentLabel" );
    tagGridLayout->addWidget( lTrackCommentLabel, 2, 1 );
    tTrackComment = new KTextEdit( tagGroupBox, "tTrackComment" );
    trackCommentBox->addWidget( tTrackComment );
    tTrackComment->setFixedHeight( 65 );
    connect( tTrackComment, TQ_SIGNAL(textChanged()),
               this, TQ_SLOT(trackCommentChanged())
             );
    pTrackCommentEdit = new KPushButton( " ", tagGroupBox, "pTrackCommentEdit" );
    pTrackCommentEdit->setPixmap( iconLoader->loadIcon("kwrite",TDEIcon::Small) );
    pTrackCommentEdit->setFixedSize( lTrackTitle->sizeHint().height(), lTrackTitle->sizeHint().height() );
    pTrackCommentEdit->hide();
    trackCommentBox->addWidget( pTrackCommentEdit );
    connect( pTrackCommentEdit, TQ_SIGNAL(clicked()),
               this, TQ_SLOT(editTrackCommentClicked())
             );

    // draw a horizontal line
    TQFrame* lineFrame = new TQFrame( this, "lineFrame" );
    lineFrame->setFrameShape( TQFrame::HLine );
    lineFrame->setFrameShadow( TQFrame::Sunken );
    lineFrame->setFrameShape( TQFrame::HLine );
    gridLayout->addWidget( lineFrame, 3, 0 );
    gridLayout->setRowSpacing( 3, 16 );

    // add a horizontal box layout for the control elements
    TQHBoxLayout* controlBox = new TQHBoxLayout( -1, "controlBox" );
    gridLayout->addLayout( controlBox, 4, 0 );

    // add the control elements
    pSaveCue = new KPushButton( iconLoader->loadIcon("document-save",TDEIcon::Small), i18n("Save cuesheet ..."), this, "pSaveCue" );
    controlBox->addWidget( pSaveCue );
    connect( pSaveCue, TQ_SIGNAL(clicked()),
               this, TQ_SLOT(saveCuesheetClicked())
             );
    controlBox->addStretch();

    cAdd = new ComboButton( this, "cAdd" );
    cAdd->insertItem( iconLoader->loadIcon("document-open",TDEIcon::Small),i18n("Add all tracks") );
    cAdd->insertItem( iconLoader->loadIcon("document-open",TDEIcon::Small),i18n("Add selected tracks") );
    RipperPlugin* plugin = config->getCurrentRipper();
    if( plugin != 0 && plugin->rip.full_disc.enabled ) cAdd->insertItem( iconLoader->loadIcon("media-optical-cdaudio-unmounted",TDEIcon::Small),i18n("Add full CD as one file") );
    //cAdd->setSizeMode( ComboButton::Min );
    controlBox->addWidget( cAdd );
    connect( cAdd, TQ_SIGNAL(clicked(int)),
               this, TQ_SLOT(addClicked(int))
             );
    pCancel = new KPushButton( iconLoader->loadIcon("cancel",TDEIcon::Small), i18n("Cancel"), this, "pCancel" );
    controlBox->addWidget( pCancel );
    connect( pCancel, TQ_SIGNAL(clicked()),
               this, TQ_SLOT(reject())
             );

    // delete the icon loader object
    delete iconLoader;

    bool various_artists = false;
    bool various_composer = false;
    TQString artist = "";
    TQString composer = "";
    TQString album = "";
    int disc = 0;
    int year = 0;
    TQString genre = "";

    device = cdManager->newCDDevice( _device );
    // don't execute the dialog, if no audio cd was found
    noCD = device.isEmpty();

    TQValueList<TagData*> tags = cdManager->getTrackList( device );
    for( TQValueList<TagData*>::Iterator it = tags.begin(); it != tags.end(); ++it ) {
        if( artist == "" ) artist = (*it)->artist;
        else if( artist != (*it)->artist ) various_artists = true;

        if( composer == "" ) composer = (*it)->composer;
        else if( composer != (*it)->composer ) various_composer = true;

        if( album == "" ) album = (*it)->album;
        if( disc == 0 ) disc = (*it)->disc;
        if( year == 0 ) year = (*it)->year;
        if( genre == "" ) genre = (*it)->genre;

        new TDEListViewItem( trackList, TQString().sprintf("%02i",(*it)->track), (*it)->artist, (*it)->composer, (*it)->title, TQString().sprintf("%i:%02i",(*it)->length/60,(*it)->length%60) );
    }
    trackList->setSorting( -1 );

    // fill in the cd information
    if( various_artists ) cArtist->setCurrentItem( 0 );
    else cArtist->setCurrentText( artist );
    artistChanged( cArtist->currentText() );

    if( various_composer ) cComposer->setCurrentItem( 0 );
    else cComposer->setCurrentText( composer );
    composerChanged( cComposer->currentText() );

    lAlbum->setText( album );
    if( disc != 0 ) iDisc->setValue( disc );
    if( year != 0 ) iYear->setValue( year );
    cGenre->setCurrentText( genre );

    //trackList->setCurrentItem( trackList->firstChild() );
    trackList->setSelected( trackList->firstChild(), true );

    pTrackUp->setEnabled( false );
    if( trackList->firstChild() != 0 ) {
        if( trackList->firstChild()->itemBelow() != 0 ) {
            pTrackDown->setEnabled( true );
        }
        else {
            pTrackDown->setEnabled( false );
        }
    }
    else {
        pTrackDown->setEnabled( false );
    }
}

CDOpener::~CDOpener()
{}

int CDOpener::columnByName( const TQString& name )
{
    for( int i = 0; i < trackList->columns(); ++i ) {
        if( trackList->columnText( i ) == name ) return i;
    }
    return -1;
}

void CDOpener::trackUpPressed()
{
    TQListViewItem* item = selectedItems.first()->itemAbove();

    if( item != 0 ) {
        item->setSelected( true );
        trackList->repaintItem( item );
        trackList->ensureItemVisible( item );
    }
    else {
        return; // NULL pointer (cannot be)
    }

    for( TQValueList<TQListViewItem*>::Iterator it = selectedItems.begin(); it != selectedItems.end(); ++it ) {
        (*it)->setSelected( false );
        trackList->repaintItem( *it );
    }

    if( item->itemAbove() == 0 ) {
        pTrackUp->setEnabled( false );
    }

    pTrackDown->setEnabled( true );

    trackChanged();
}

void CDOpener::trackDownPressed()
{
    TQListViewItem* item = selectedItems.last()->itemBelow();

    if( item != 0 ) {
        item->setSelected( true );
        trackList->repaintItem( item );
        trackList->ensureItemVisible( item );
    }
    else {
        return; // NULL pointer (cannot be)
    }

    for( TQValueList<TQListViewItem*>::Iterator it = selectedItems.begin(); it != selectedItems.end(); ++it ) {
        (*it)->setSelected( false );
        trackList->repaintItem( *it );
    }

    pTrackUp->setEnabled( true );

    if( item->itemBelow() == 0 ) {
        pTrackDown->setEnabled( false );
    }

    trackChanged();
}

void CDOpener::trackChanged()
{
    // NOTE if no track is selected soundkonverter could use the current item as default item (like qlistview does)
    int i = 0;

    // rebuild the list of the selected tracks
    selectedTracks.clear();
    selectedItems.clear();
    for( TQListViewItem *item = trackList->firstChild(); item != NULL; item = item->nextSibling() ) {
        i++;
        if( item->isSelected() ) {
            selectedTracks.append( i );
            selectedItems.append( item );
        }
    }

    // insert the new values
    if( selectedTracks.count() < 1 ) {
        pTrackUp->setEnabled( false );
        pTrackDown->setEnabled( false );

        lTrackTitle->setEnabled( false );
        lTrackTitle->setText( "" );
        pTrackTitleEdit->hide();
        lTrackArtist->setEnabled( false );
        lTrackArtist->setText( "" );
        pTrackArtistEdit->hide();
        lTrackComposer->setEnabled( false );
        lTrackComposer->setText( "" );
        pTrackComposerEdit->hide();
        tTrackComment->setEnabled( false );
        tTrackComment->setReadOnly( true );
        tTrackComment->setText( "" );
        pTrackCommentEdit->hide();

        return;
    }
    else if( selectedTracks.count() > 1 ) {
        if( selectedItems.first()->itemAbove() != 0 ) pTrackUp->setEnabled( true );
        else pTrackUp->setEnabled( false );

        if( selectedItems.last()->itemBelow() != 0 ) pTrackDown->setEnabled( true );
        else pTrackDown->setEnabled( false );

        TQString trackListString = "";
        if( selectedTracks.count() == trackList->childCount() ) {
            trackListString = i18n("All tracks");
        }
        else {
            trackListString = i18n("Tracks") + TQString().sprintf(" %02i",selectedTracks.first());
            TQValueList<int>::Iterator track = selectedTracks.begin();
            track++;
            for( ; track != selectedTracks.end(); ++track ) {
                trackListString += TQString().sprintf(", %02i",*track);
            }
        }
        tagGroupBox->setTitle( trackListString );

        TQString title = cdManager->getTags( device, selectedTracks.first() )->title;
        bool equalTitles = true;
        TQString artist = cdManager->getTags( device, selectedTracks.first() )->artist;
        bool equalArtists = true;
        TQString composer = cdManager->getTags( device, selectedTracks.first() )->composer;
        bool equalComposers = true;
        TQString comment = cdManager->getTags( device, selectedTracks.first() )->comment;
        bool equalComments = true;
        for( TQValueList<int>::Iterator track = selectedTracks.begin(); track != selectedTracks.end(); ++track ) {
            TagData* tags = cdManager->getTags( device, *track );

            if( title != tags->title ) equalTitles = false;
            if( artist != tags->artist ) equalArtists = false;
            if( composer != tags->composer ) equalComposers = false;
            if( comment != tags->comment ) equalComments = false;
        }

        if( equalTitles ) {
            lTrackTitle->setEnabled( true );
            lTrackTitle->setText( title );
            pTrackTitleEdit->hide();
        }
        else {
            lTrackTitle->setEnabled( false );
            lTrackTitle->setText( "" );
            pTrackTitleEdit->show();
        }

        if( cArtist->currentText() == i18n("Various Artists") && equalArtists ) {
            lTrackArtist->setEnabled( true );
            lTrackArtist->setText( artist );
            pTrackArtistEdit->hide();
        }
        else if( cArtist->currentText() == i18n("Various Artists") ) {
            lTrackArtist->setEnabled( false );
            lTrackArtist->setText( "" );
            pTrackArtistEdit->show();
        }
        else {
            lTrackArtist->setEnabled( false );
            lTrackArtist->setText( cArtist->currentText() );
            pTrackArtistEdit->hide();
        }

        if( cComposer->currentText() == i18n("Various Composer") && equalComposers ) {
            lTrackComposer->setEnabled( true );
            lTrackComposer->setText( composer );
            pTrackComposerEdit->hide();
        }
        else if( cComposer->currentText() == i18n("Various Composer") ) {
            lTrackComposer->setEnabled( false );
            lTrackComposer->setText( "" );
            pTrackComposerEdit->show();
        }
        else {
            lTrackComposer->setEnabled( false );
            lTrackComposer->setText( cComposer->currentText() );
            pTrackComposerEdit->hide();
        }

        if( equalComments ) {
            tTrackComment->setEnabled( true );
            tTrackComment->setReadOnly( false );
            tTrackComment->setText( comment );
            pTrackCommentEdit->hide();
        }
        else {
            tTrackComment->setEnabled( false );
            tTrackComment->setReadOnly( true );
            tTrackComment->setText( "" );
            pTrackCommentEdit->show();
        }
    }
    else {
        if( selectedItems.first()->itemAbove() != 0 ) pTrackUp->setEnabled( true );
        else pTrackUp->setEnabled( false );

        if( selectedItems.first()->itemBelow() != 0 ) pTrackDown->setEnabled( true );
        else pTrackDown->setEnabled( false );

        tagGroupBox->setTitle( i18n("Track") + TQString().sprintf(" %02i",selectedTracks.first()) );

        TagData* tags = cdManager->getTags( device, selectedTracks.first() );
        lTrackTitle->setEnabled( true );
        lTrackTitle->setText( tags->title );
        pTrackTitleEdit->hide();
        if( cArtist->currentText() == i18n("Various Artists") ) {
            lTrackArtist->setEnabled( true );
            lTrackArtist->setText( tags->artist );
            pTrackArtistEdit->hide();
        }
        else {
            lTrackArtist->setEnabled( false );
            lTrackArtist->setText( cArtist->currentText() );
            pTrackArtistEdit->hide();
        }
        if( cComposer->currentText() == i18n("Various Composer") ) {
            lTrackComposer->setEnabled( true );
            lTrackComposer->setText( tags->composer );
            pTrackComposerEdit->hide();
        }
        else {
            lTrackComposer->setEnabled( false );
            lTrackComposer->setText( cComposer->currentText() );
            pTrackComposerEdit->hide();
        }
        tTrackComment->setEnabled( true );
        tTrackComment->setReadOnly( false );
        tTrackComment->setText( tags->comment );
        pTrackCommentEdit->hide();
    }
}

void CDOpener::artistChanged( const TQString& text )
{
    if( text == i18n("Various Artists") ) {
        trackList->adjustColumn( columnByName( i18n("Artist") ) );
    }
    else {
        trackList->setColumnWidth( columnByName( i18n("Artist") ), 0 );
    }

    trackChanged();
}

void CDOpener::composerChanged( const TQString& text )
{
    if( text == i18n("Various Composer") ) {
        trackList->adjustColumn( columnByName( i18n("Composer") ) );
    }
    else {
        trackList->setColumnWidth( columnByName( i18n("Composer") ), 0 );
    }

    trackChanged();
}

void CDOpener::trackTitleChanged( const TQString& text )
{
    if( !lTrackTitle->isEnabled() ) return;

    for( TQValueList<TQListViewItem*>::Iterator it = selectedItems.begin(); it != selectedItems.end(); ++it ) {
        (*it)->setText( columnByName( i18n("Title") ), text );
    }
    for( TQValueList<int>::Iterator it = selectedTracks.begin(); it != selectedTracks.end(); ++it ) {
        TagData* tags = cdManager->getTags( device, *it );
        tags->title = text;
    }
}

void CDOpener::trackArtistChanged( const TQString& text )
{
    if( !lTrackArtist->isEnabled() ) return;

    for( TQValueList<TQListViewItem*>::Iterator it = selectedItems.begin(); it != selectedItems.end(); ++it ) {
        (*it)->setText( columnByName( i18n("Artist") ), text );
    }
    for( TQValueList<int>::Iterator it = selectedTracks.begin(); it != selectedTracks.end(); ++it ) {
        TagData* tags = cdManager->getTags( device, *it );
        tags->artist = text;
    }
}

void CDOpener::trackComposerChanged( const TQString& text )
{
    if( !lTrackComposer->isEnabled() ) return;

    for( TQValueList<TQListViewItem*>::Iterator it = selectedItems.begin(); it != selectedItems.end(); ++it ) {
        (*it)->setText( columnByName( i18n("Composer") ), text );
    }
    for( TQValueList<int>::Iterator it = selectedTracks.begin(); it != selectedTracks.end(); ++it ) {
        TagData* tags = cdManager->getTags( device, *it );
        tags->composer = text;
    }
}

void CDOpener::trackCommentChanged()
{
    TQString text = tTrackComment->text();

    if( !tTrackComment->isEnabled() ) return;

    for( TQValueList<int>::Iterator it = selectedTracks.begin(); it != selectedTracks.end(); ++it ) {
        TagData* tags = cdManager->getTags( device, *it );
        tags->comment = text;
    }
}

void CDOpener::editTrackTitleClicked()
{
    lTrackTitle->setEnabled( true );
    lTrackTitle->setFocus();
    pTrackTitleEdit->hide();
    trackTitleChanged( lTrackTitle->text() );
}

void CDOpener::editTrackArtistClicked()
{
    lTrackArtist->setEnabled( true );
    lTrackArtist->setFocus();
    pTrackArtistEdit->hide();
    trackArtistChanged( lTrackArtist->text() );
}

void CDOpener::editTrackComposerClicked()
{
    lTrackComposer->setEnabled( true );
    lTrackComposer->setFocus();
    pTrackComposerEdit->hide();
    trackComposerChanged( lTrackComposer->text() );
}

void CDOpener::editTrackCommentClicked()
{
    tTrackComment->setEnabled( true );
    tTrackComment->setReadOnly( false );
    tTrackComment->setFocus();
    pTrackCommentEdit->hide();
    trackCommentChanged();
}

void CDOpener::addClicked( int index )
{
    if( index == 0 )
    {
        TQValueList<int> allTracks;

        // TODO save all options (album artist, disc, genre, etc.)
        for( int it = 1; it <= cdManager->getTrackCount(device); ++it ) {
            TagData* tags = cdManager->getTags( device, it );
            if( cArtist->currentText() != i18n("Various Artists") ) tags->artist = cArtist->currentText();
            if( cComposer->currentText() != i18n("Various Composer") ) tags->composer = cComposer->currentText();
            tags->album = lAlbum->text();
            tags->disc = iDisc->value();
            tags->year = iYear->value();
            tags->genre = cGenre->currentText();
            allTracks += it;
        }
        emit addTracks( device, allTracks );
    }
    else if( index == 1 )
    {
        // TODO save all options (album artist, disc, genre, etc.)
        for( TQValueList<int>::Iterator it = selectedTracks.begin(); it != selectedTracks.end(); ++it ) {
            TagData* tags = cdManager->getTags( device, *it );
            if( cArtist->currentText() != i18n("Various Artists") ) tags->artist = cArtist->currentText();
            if( cComposer->currentText() != i18n("Various Composer") ) tags->composer = cComposer->currentText();
            tags->album = lAlbum->text();
            tags->disc = iDisc->value();
            tags->year = iYear->value();
            tags->genre = cGenre->currentText();
        }
        emit addTracks( device, selectedTracks );
    }
    else
    {
        // TODO save all options (album artist, disc, genre, etc.)
        cdManager->setDiscTags( device,
                new TagData( cArtist->currentText(), cComposer->currentText(),
                            lAlbum->text(), /*cArtist->currentText() + " - " + */lAlbum->text(),
                            cGenre->currentText(), "",
                            1, iDisc->value(), iYear->value(),
                            cdManager->getTimeCount(device) ) );
        emit addDisc( device );
    }
    accept();
}

// void CDOpener::addAsOneTrackClicked()
// {
//     // TODO save all options (album artist, disc, genre, etc.)
//     cdManager->setDiscTags( device,
//             new TagData( cArtist->currentText(), cComposer->currentText(),
//                           lAlbum->text(), /*cArtist->currentText() + " - " + */lAlbum->text(),
//                           cGenre->currentText(), "",
//                           1, iDisc->value(), iYear->value(),
//                           cdManager->getTimeCount(device) ) );
// 
//     emit addDisc( device );
//     accept();
// }

void CDOpener::saveCuesheetClicked()
{
    TQString filename = KFileDialog::getSaveFileName( TQDir::homeDirPath(), "*.cue" );
    if( filename.isEmpty() ) return;

    TQFile cueFile( filename );
    if( cueFile.exists() ) {
        int ret = KMessageBox::questionYesNo( this,
                    i18n("A file with this name already exists.\n\nDo you want to overwrite the existing one?"),
                          i18n("File already exists") );
        if( ret == KMessageBox::No ) return;
    }
    if( !cueFile.open( IO_WriteOnly ) ) return;

    TQString content;

    content.append( "TITLE \"" + lAlbum->text() + "\"\n" );
    content.append( "PERFORMER \"" + cArtist->currentText() + "\"\n" );
    content.append( "FILE \"\" MP3\n" );

    int INDEX = 0;
    bool addFrames = false;
    TQValueList<TagData*> tags = cdManager->getTrackList( device );
    for( TQValueList<TagData*>::Iterator it = tags.begin(); it != tags.end(); ++it ) {
        content.append( TQString().sprintf("  TRACK %02i AUDIO\n",(*it)->track ) );
        content.append( "    TITLE \"" + (*it)->title + "\"\n" );
        content.append( "    PERFORMER \"" + (*it)->artist + "\"\n" );
        if( addFrames ) {
            content.append( TQString().sprintf("    INDEX 01 %02i:%02i:37\n",INDEX/60,INDEX%60) );
            INDEX++;
            addFrames = false;
        }
        else {
            content.append( TQString().sprintf("    INDEX 01 %02i:%02i:00\n",INDEX/60,INDEX%60) );
            addFrames = true;
        }

        INDEX += (*it)->length;
    }

    TQTextStream ts( &cueFile );
    ts << content;

    cueFile.close();
}

#include "cdopener.moc"
