/***************************************************************************
 *   Copyright (C) 2005 by Roland Weigert                                  *
 *   roweigert@t-online.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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#define SCHREIBEN TRUE

#include "tagdialog.h"

extern databasewrapper *database;
extern verzeichnis *verzeichnisbaum;
extern rcdatei settingsfile;
extern playerinterface *playerlink;

tagdialog::tagdialog(QWidget *pointer)
{
    coverdialog=NULL;
    tagschanged=FALSE;
    rescan=FALSE;
    nopicture=FALSE;
    verzeichnisbaum=NULL;
    loader=new KIconLoader();
    QPixmap pixmap;
    QString picname;
    //Gr�se fr alle Comboboxen festlegen
    QSize combosize(300,30);
    QSize spinboxsize(80,30);
    QSize infozeilesize(1280,30);
    //Treeview zum Files selektieren
    tagdialoglayout=new QVBoxLayout(pointer);
    splitteraufteilung=new QSplitter(QSplitter::Horizontal,pointer);
    tagdialoglayout->addWidget(splitteraufteilung);
    //tagdialoglayout->addWidget(infozeile);
    hauptbox=new QGroupBox(9,Qt::Vertical,"ID3-Tags",splitteraufteilung,QString::null);
    hauptbox->setInsideMargin(10);
    auswahlbaum=new fileselector(splitteraufteilung);
    QToolTip::add
        (auswahlbaum,i18n("Drop files or directories in here, or set tagger-directory in settings."));
    splitteraufteilung->moveToFirst(auswahlbaum);
    //Alle Layoutzeiger anlegen
    mainlayout=new QHBoxLayout(pointer);
    mainlayout->addWidget(splitteraufteilung);
    mainlayout->setSpacing(5);
    mainlayout->setMargin(5);
    //Alle Gruppierungsboxen erzeugen
    gruppegroupbox=new QGroupBox(2,Qt::Horizontal,hauptbox);
    albumgroupbox=new QGroupBox(2,Qt::Horizontal,hauptbox);
    titelgroupbox=new QGroupBox(3,Qt::Horizontal,hauptbox);
    genregroupbox=new QGroupBox(2,Qt::Horizontal,hauptbox);
    jahrgroupbox=new QGroupBox(2,Qt::Horizontal,hauptbox);
    covergroupbox=new QGroupBox(2,Qt::Horizontal,"CD-Cover",hauptbox);
    //Zeile1 Gruppe
    artistlabel=new QLabel(i18n("artist"),gruppegroupbox);
    artistbox=new QComboBox(SCHREIBEN,gruppegroupbox);
    artistbox->setAutoCompletion(settingsfile.autocomplete);
    artistbox->setDuplicatesEnabled(FALSE);
    artistbox->setMinimumSize(combosize);
    //Zeile2 Album
    albumlabel=new QLabel(i18n("album"),albumgroupbox);
    albumbox=new QComboBox(SCHREIBEN,albumgroupbox);
    albumbox->setAutoCompletion(settingsfile.autocomplete);
    albumbox->setDuplicatesEnabled(FALSE);
    albumbox->setMinimumSize(combosize);
    //Zeile3 Track und Titel
    tracklabel=new QLabel(i18n("track"),titelgroupbox);
    tracknumberbox=new QSpinBox(titelgroupbox);
    tracknumberbox->setRange(0,99);
    tracknumberbox->setMinimumSize(spinboxsize);
    tracknumberbox->setMaximumSize(spinboxsize);
    trackbox=new QComboBox(SCHREIBEN,titelgroupbox);
    trackbox->setAutoCompletion(settingsfile.autocomplete);
    trackbox->setDuplicatesEnabled(FALSE);
    trackbox->setMinimumSize(combosize);
    //Zeile4 genre
    genrelabel=new QLabel(i18n("genre"),genregroupbox);
    genrebox=new QComboBox(SCHREIBEN,genregroupbox);
    genrebox->setDuplicatesEnabled(FALSE);
    genrebox->setAutoCompletion(settingsfile.autocomplete);
    genrebox->setMinimumSize(combosize);
    //Zeile 5 Jahr
    yearlabel=new QLabel(i18n("releaseyear"),jahrgroupbox);
    yearbox=new QSpinBox(jahrgroupbox);
    yearbox->setRange(0,9999);
    yearbox->setMinimumSize(spinboxsize);
    yearbox->setMaximumSize(spinboxsize);
    //zeile6 Coverbild
    coverlabel=new QLabel(covergroupbox);
    coverlabel->setText(i18n("no cover set"));
    covercontrols=new QVBox(covergroupbox);
    loadcoverbutton=new QPushButton(i18n("Select Cover"),covercontrols);
    removecoverbutton=new QPushButton(i18n("Remove Cover"),covercontrols);
    findcoverbutton=new QPushButton(i18n("Search for Cover"),covercontrols);
    loadcoverbutton->setEnabled(FALSE);
    removecoverbutton->setEnabled(FALSE);
    findcoverbutton->setEnabled(FALSE);
    picname="filesave.png";
    pixmap=loader->loadIcon(picname,KIcon::Desktop);
    QIconSet buttonset(pixmap);
    speichernknopf=new QPushButton(i18n("save file"),hauptbox);
    speichernknopf->setIconSet(buttonset);
    picname="wizard.png";
    pixmap=loader->loadIcon(picname,KIcon::Desktop);
    buttonset=QIconSet(pixmap);
    cleanupbutton=new QPushButton(i18n("Cleanup"),hauptbox);
    cleanupbutton->setIconSet(buttonset);
    guessbutton=new QPushButton(i18n("Guess tags"),hauptbox);
    guessbutton->setIconSet(buttonset);
    infozeile=new QStatusBar(pointer,"Status");
    infozeile->setSizeGripEnabled(FALSE);
    infozeile->setMaximumSize(infozeilesize);
    //alle Eingaben auf rechter Seite sperren, bis Datei(en) ausgesucht sind
    infozeile->message(i18n("no files selected"));
    eingabensperren();
    if (settingsfile.databasetype)
        boxenholen();
    //Connections for the comboboxes
    taggercontext=new flexiblecontext(this,i18n("Contexthelp"));
    connect(taggercontext,SIGNAL(readnewdir()),SLOT(listboxholen()));
    connect(artistbox,SIGNAL(textChanged(const QString &)),SLOT(artistChanged()));
    connect(albumbox,SIGNAL(textChanged(const QString &)),SLOT(albumChanged()));
    connect(trackbox,SIGNAL(textChanged(const QString &)),SLOT(trackChanged()));
    connect(tracknumberbox,SIGNAL(valueChanged(int)),this,SLOT(tracknumberChanged(int)));
    connect(yearbox,SIGNAL(valueChanged(int)),this,SLOT(yearChanged()));
    connect(genrebox,SIGNAL(textChanged(const QString &)),SLOT(genreChanged()));
    connect(speichernknopf,SIGNAL(clicked()),this,SLOT(tagschreiben()));
    connect(cleanupbutton,SIGNAL(clicked()),this,SLOT(cleanupslot()));
    connect(guessbutton,SIGNAL(clicked()),this,SLOT(guessslot()));
    connect(loadcoverbutton,SIGNAL(clicked()),this,SLOT(bildladen()));
    connect(findcoverbutton,SIGNAL(clicked()),this,SLOT(findcoverslot()));
    connect(removecoverbutton,SIGNAL(clicked()),this,SLOT(removecoverslot()));
    //connect(auswahlbaum,SIGNAL(clicked(QListViewItem *)),this,SLOT(multitagupdate()));
    connect(auswahlbaum,SIGNAL(returnPressed(QListViewItem *)),this,SLOT(multitagupdate()));
    connect(auswahlbaum,SIGNAL(spacePressed(QListViewItem *)),this,SLOT(multitagupdate()));
    connect(auswahlbaum,SIGNAL(contextMenuRequested(QListViewItem *,const QPoint &,int)),SLOT(showcontext(QListViewItem *,const QPoint &)));
    connect(auswahlbaum,SIGNAL(mouseButtonPressed(int,QListViewItem *,const QPoint &,int)),SLOT(checkmousebutton(int,QListViewItem *)));
    delete loader;
}

tagdialog::~tagdialog()
{
    cerr<<"tagdialog destructor"<<endl;
    delete taggercontext;
    delete infozeile;
    delete loadcoverbutton;
    delete removecoverbutton;
    delete findcoverbutton;
    delete covercontrols;
    delete artistlabel;
    delete albumlabel;
    delete tracklabel;
    delete genrelabel;
    delete yearlabel;
    delete artistbox;
    delete albumbox;
    delete trackbox;
    delete genrebox;
    delete auswahlbaum;
    delete tracknumberbox;
    delete yearbox;
    delete speichernknopf;
    delete cleanupbutton;
    delete guessbutton;
    delete gruppegroupbox;
    delete albumgroupbox;
    delete titelgroupbox;
    delete genregroupbox;
    delete jahrgroupbox;
    delete coverlabel;
    delete covergroupbox;
    delete hauptbox;
    delete splitteraufteilung;
    delete mainlayout;
    delete tagdialoglayout;
}

void tagdialog::setvervollstaendigen(bool vervollstaendigen)
{
    artistbox->setAutoCompletion(vervollstaendigen);
    albumbox->setAutoCompletion(vervollstaendigen);
    trackbox->setAutoCompletion(vervollstaendigen);
    genrebox->setAutoCompletion(vervollstaendigen);
}

void tagdialog::listboxholen()
{
    //First check if some tags are changed
    //Check for edited tags first
    int result=0;
    while(tagschanged&&!result)
    {
        if (!(result=QMessageBox::warning(0,i18n("Save files"),i18n("Some files have edited tags. Do want to save your files first?"),"Save first",i18n("Continue"),i18n("cancel"),1)))
            savemodified();
    }
    if ((result==1)||(result==0&&!tagschanged))
    {
        progressmainwindow *progresswindow=new progressmainwindow(FALSE);
        progresswindow->show();
        if (verzeichnisbaum)
            {
            delete verzeichnisbaum;
            verzeichnisbaum=NULL;
            }
        //Check if the dir, we want to read still exists
        QFileInfo checkdir(settingsfile.reading_dir);
        if (checkdir.exists()&&checkdir.isDir())
        {
            verzeichnisbaum=new verzeichnis(settingsfile.reading_dir,auswahlbaum);
            verzeichnisbaum->abbruch=FALSE;
            auswahlbaum->clear();//alten Baum l�chen
            if (!verzeichnisbaum->abortscan)
            {
                // Lehren Ordner mit Working-Dir-Path als namen generieren
                fileselectoritem *startordner=new fileselectoritem(auswahlbaum,settingsfile.reading_dir);
                //startordner->setExpandable(TRUE);
                //Restlichen Baum holen
                progressinfo *scanprocess=progresswindow->startInfo(i18n("Scanning for files"));
                connect(scanprocess,SIGNAL(cancelled()),verzeichnisbaum,SLOT(abbruchslot()));
                verzeichnisbaum->treemodus(settingsfile.reading_dir,startordner,scanprocess);
                progresswindow->killProgress(scanprocess);
                //Falls brauchbare Dateien gefunden,und MYSQL benutzt wird, Dateien mit Datenbank vergleichen
                if ((verzeichnisbaum->musikgefunden())&&(settingsfile.databasetype)&&!verzeichnisbaum->abortscan&&!rescan)
                {
                    progresswithbar *progressbar=progresswindow->startProgress(i18n("Matching directories to MySQL"),verzeichnisbaum->dzaehler);
                    verzeichnisbaum->scanverzeichnis(progressbar);
                    delete progressbar;
                }
                startordner->setOpen(TRUE);
                delete progresswindow;
            }
            else
            {
                delete progresswindow;
            }
        }
        else
        {
            //tell user that the reading_dir is not existing,and set users homedirectory as new reading dir
            QMessageBox::information(this,i18n("Read error"),i18n("The reading directory does not exist."));
            if (verzeichnisbaum)
            {
            delete verzeichnisbaum;
            verzeichnisbaum=NULL;
            }
            delete progresswindow;
        }
        tagschanged=FALSE;
        //call multitagupdate, to get actual display of selected files
        multitagupdate();
    }
}

void tagdialog::tagupdate(QListViewItem *inhalt)
{
    disconnect(artistbox,SIGNAL(textChanged(const QString &)),this,SLOT(artistChanged()));
    disconnect(albumbox,SIGNAL(textChanged(const QString &)),this,SLOT(albumChanged()));
    disconnect(trackbox,SIGNAL(textChanged(const QString &)),this,SLOT(trackChanged()));
    disconnect(tracknumberbox,SIGNAL(valueChanged(int)),this,SLOT(tracknumberChanged(int)));
    disconnect(yearbox,SIGNAL(valueChanged(int)),this,SLOT(yearChanged()));
    disconnect(genrebox,SIGNAL(textChanged(const QString &)),this,SLOT(genreChanged()));
    //first check if this file is already stored in memory
    if(!static_cast<fileselectoritem *>(inhalt)->
            tagloaded)
    {
        aktuelledatei=static_cast<fileselectoritem *>(inhalt)->itemfilename;
        if (!aktuelledatei.isEmpty()&&singleselect)
        {
            mediafile *file=new mediafile(aktuelledatei);
            if (file->readsuccess)
            {
                file->readTags();
                if (!file->isv2capable)
                {
                    //deactivate all coverstuff, because filetype does not support it
                    coverlabel->setText(i18n("No picture allowed"));
                    nopicture=TRUE;
                }
                if (file->containsTag)
                {
                    artistbox->setCurrentText(file->taginfo.artist);
                    albumbox->setCurrentText(file->taginfo.album);
                    trackbox->setCurrentText(file->taginfo.title);
                    genrebox->setCurrentText(file->taginfo.genre);
                    yearbox->setValue(file->taginfo.year);
                    tracknumberbox->setValue(file->taginfo.number);
                    if (file->picturepossible)
                    {
                        file->readPicture();
                        //if taginfo has a pixmap, set it up
                        if (!file->taginfo.cdcover.isNull())
                        {
                            //if we have an image, set it
                            frontcover=file->taginfo.cdcover;
                            QImage scaledcover;
                            scaledcover=frontcover;
                            scaledcover=scaledcover.smoothScale(150,150,QImage::ScaleMin);
                            coverlabel->setPixmap(scaledcover);
                        }

                    }
                }
                else
                {
                    //Tags are empty,so set all boxes empty
                    artistbox->setCurrentText("");
                    albumbox->setCurrentText("");
                    trackbox->setCurrentText("");
                    genrebox->setCurrentText("");
                    yearbox->setValue(0);
                    tracknumberbox->setValue(0);
                }
                //Enter all read infos in our fileselectoritem also
                //Do a cast with that pointer before, so we can store our values
                fileselectoritem *actualitem=static_cast<fileselectoritem *>(inhalt);
                actualitem->taginfo=file->taginfo;
                actualitem->picturepossible=file->picturepossible;
                actualitem->tagloaded=TRUE;
                actualitem->tagchanged=FALSE;
            }
            else
            {
                rescan=TRUE;
            }
            delete file;
        }
    }
    else
    {
        //Load tags out of memory, to continue changing the values in memory
        fileselectoritem *actualitem=static_cast<fileselectoritem *>(inhalt);
        artistbox->setCurrentText(actualitem->taginfo.artist);
        albumbox->setCurrentText(actualitem->taginfo.album);
        trackbox->setCurrentText(actualitem->taginfo.title);
        genrebox->setCurrentText(actualitem->taginfo.genre);
        yearbox->setValue(actualitem->taginfo.year);
        tracknumberbox->setValue(actualitem->taginfo.number);
        if (actualitem->picturepossible)
        {
            frontcover=actualitem->taginfo.cdcover;
            QImage scaledcover;
            scaledcover=frontcover;
            if (!frontcover.isNull())
            {
                scaledcover=scaledcover.smoothScale(150,150,QImage::ScaleMin);
                coverlabel->setPixmap(scaledcover);
            }
        }
    }
    connect(artistbox,SIGNAL(textChanged(const QString &)),SLOT(artistChanged()));
    connect(albumbox,SIGNAL(textChanged(const QString &)),SLOT(albumChanged()));
    connect(trackbox,SIGNAL(textChanged(const QString &)),SLOT(trackChanged()));
    connect(tracknumberbox,SIGNAL(valueChanged(int)),this,SLOT(tracknumberChanged(int)));
    connect(yearbox,SIGNAL(valueChanged(int)),this,SLOT(yearChanged()));
    connect(genrebox,SIGNAL(textChanged(const QString &)),SLOT(genreChanged()));
}

void tagdialog::getselectionlist()
{
    QListViewItemIterator dircheck(auswahlbaum,QListViewItemIterator::Selected);
    while (dircheck.current())
    {
        if ((static_cast<fileselectoritem *>(dircheck.current())->isdirectory)
           )
        {
            rekursivtag(dircheck.current());
        }
        dircheck++;
    }
    this->auswahlliste.clear();
    QListViewItemIterator auswahl(auswahlbaum,QListViewItemIterator::Selected);
    itemcounter=0;
    while (auswahl.current())
    {
        if (!(static_cast<fileselectoritem *>(auswahl.current())->isdirectory)
           )
        {
            auswahlliste.append((auswahl.current()));
            itemcounter++;
        }
        auswahl++;
    }
}

void tagdialog::multitagupdate()
{
    disconnect(artistbox,SIGNAL(textChanged(const QString &)),this,SLOT(artistChanged()));
    disconnect(albumbox,SIGNAL(textChanged(const QString &)),this,SLOT(albumChanged()));
    disconnect(trackbox,SIGNAL(textChanged(const QString &)),this,SLOT(trackChanged()));
    disconnect(tracknumberbox,SIGNAL(valueChanged(int)),this,SLOT(tracknumberChanged(int)));
    disconnect(yearbox,SIGNAL(valueChanged(int)),this,SLOT(yearChanged()));
    disconnect(genrebox,SIGNAL(textChanged(const QString &)),this,SLOT(genreChanged()));
    //disconnect(auswahlbaum,SIGNAL(selectionChanged()),this,SLOT(multitagupdate()));
    //disconnect(auswahlbaum,SIGNAL(clicked(QListViewItem *)),this,SLOT(multitagupdate()));
    //clear picture out of guy.
    getselectionlist();
    nopicture=FALSE;
    eingabensperren();
    coverlabel->setText(i18n("No Picture set"));
    if (!frontcover.isNull())
        frontcover.resize(0,0);
    speichernknopf->setEnabled(FALSE);
    if (itemcounter==0)
    {
        infozeile->message(i18n("no files selected"));
        //set all Boxes to empty
        artistbox->setCurrentText("");
        albumbox->setCurrentText("");
        trackbox->setCurrentText("");
        genrebox->setCurrentText("");
        yearbox->setValue(0);
        tracknumberbox->setValue(0);
    }
    else if (itemcounter==1)
    {
        singleselect=1;
        tagupdate(auswahlliste.first());
        eingabenfreigebensingle();
        if (rescan)
        {
            listboxholen();
            rescan=FALSE;
            infozeile->message(i18n("Selected file does not exist anymore. Rescanning directory."));
        }
        else
        {
            infozeile->message(i18n("1 file selected"));
        }
    }
    else if (itemcounter>1)
    {
        progressmainwindow *progresswindow=new progressmainwindow(FALSE);
        progresswindow->show();
        progressinfoonly *progress=progresswindow->startInfoOnly(i18n("Reading in Taginformation of selected files"));
        QString bandvergleich,albumvergleich,titelvergleich,genrevergleich;
        int jahrvergleich=0,nummervergleich=0;
        singleselect=0;
        infozeile->message(i18n("%1 files selected").arg(itemcounter));
        //Stringliste fr die kompletten Dateinamen
        fileselectoritem *pfadpuffer;
        auswahlliste.first();
        long i=0;
        bandabbruch=FALSE;
        albumabbruch=FALSE;
        titelabbruch=FALSE;
        genreabbruch=FALSE;
        jahrabbruch=FALSE;
        nummerabbruch=FALSE;
        int pictureserial=0;
        bool komplettabbruch=FALSE;
        while ((i<itemcounter)&&!(komplettabbruch))
        {
            kapp->processEvents();
            bool tagstocheck=FALSE;
            pfadpuffer=static_cast<fileselectoritem *>(auswahlliste.current());
            if (!pfadpuffer->tagloaded)
            {
                aktuelledatei=pfadpuffer->itemfilename;
                mediafile *file=new mediafile(aktuelledatei);
                if (file->readsuccess)
                {
                    tagstocheck=TRUE;
                    file->readTags();
                    if (!file->isv2capable)
                    {
                        //deactivate all coverstuff, because filetype does not support it
                        coverlabel->setText(i18n("No picture allowed"));
                        nopicture=TRUE;
                    }
                    else if(file->picturepossible)
                    {
                        file->readPicture();
                        pfadpuffer->picturepossible=TRUE;
                    }
                    pfadpuffer->taginfo=file->taginfo;
                    pfadpuffer->tagloaded=TRUE;
                    delete file;
                }
                else
                {
                    rescan=TRUE;
                }
            }
            else
            {
                tagstocheck=TRUE;
                //we don't need to do a thing to load the values here, since we always use the pfadpuffer-pointer
            }
            if (i==0&&tagstocheck)//Read in the comparstrings, and the picture of the first file
            {
                //Vergleichswerte in Strings einlesen
                bandvergleich=pfadpuffer->taginfo.artist;
                albumvergleich=pfadpuffer->taginfo.album;
                titelvergleich=pfadpuffer->taginfo.title;
                genrevergleich=pfadpuffer->taginfo.genre;
                jahrvergleich=pfadpuffer->taginfo.year;
                nummervergleich=pfadpuffer->taginfo.number;
                if (pfadpuffer->picturepossible&&!nopicture)
                {
                    if (!pfadpuffer->taginfo.cdcover.isNull())
                    {
                        //if we have an image, set it
                        frontcover=pfadpuffer->taginfo.cdcover;
                        QImage scaledcover;
                        scaledcover=pfadpuffer->taginfo.cdcover.convertToImage();
                        pictureserial=scaledcover.numBytes();//save the size in bytes for comparison
                        scaledcover=scaledcover.smoothScale(150,150,QImage::ScaleMin);
                        coverlabel->setPixmap(scaledcover);
                    }
                }
            }
            else if (i>0&&tagstocheck)
            {
                //Check if the strings match the compare-values
                //To keep that nice and easy, make a pointer to the used tags
                mediatag *Song=NULL;
                /*Read in the cover of the last file, and compare the size with the first one, if existing
                *If they match, keep the cover, if not set cover as not existing*/
                Song=&pfadpuffer->taginfo;
                if (pictureserial&&!nopicture)
                {
                    if (pfadpuffer->picturepossible)
                    {
                        if (!pfadpuffer->taginfo.cdcover.isNull())
                        {
                            QImage secondpicture=pfadpuffer->taginfo.cdcover.convertToImage();
                            if(pictureserial!=secondpicture.numBytes())
                            {
                                coverlabel->setText(i18n("no cover set"));
                                frontcover.resize(0,0);//delete the set picture
                                pictureserial=0;//stop searching for next file
                            }
                        }
                    }
                }
                if (Song)
                {
                    if (!bandvergleich.isEmpty()||bandabbruch)
                    {
                        if (bandvergleich.compare(Song->artist))
                        {
                            bandvergleich="";
                            bandabbruch=TRUE;
                        }
                    }
                    if (!albumvergleich.isEmpty()||albumabbruch)
                    {
                        if (albumvergleich.compare(Song->album))
                        {
                            albumvergleich="";
                            albumabbruch=TRUE;
                        }
                    }
                    if (!titelvergleich.isEmpty()||titelabbruch)
                    {
                        if (titelvergleich.compare(Song->title))
                        {
                            titelvergleich="";
                            titelabbruch=TRUE;
                        }
                    }
                    if (!genrevergleich.isEmpty()||genreabbruch)
                    {
                        if (genrevergleich.compare(Song->genre))
                        {
                            genrevergleich="";
                            genreabbruch=TRUE;
                        }
                    }
                    if (!jahrabbruch)
                    {
                        if (!(jahrvergleich==Song->year))
                        {
                            jahrvergleich=0;
                            jahrabbruch=TRUE;
                        }
                    }
                    if (!nummerabbruch)
                    {
                        if (!(nummervergleich==Song->number))
                        {
                            nummervergleich=0;
                            nummerabbruch=TRUE;
                        }
                    }
                }
                else
                    komplettabbruch=TRUE;
            }
            if (rescan==TRUE)
                komplettabbruch=TRUE;
            auswahlliste.next();
            i++;
        }
        delete progress;
        delete progresswindow;
        if (!rescan)
        {
            artistbox->setCurrentText(bandvergleich);
            albumbox->setCurrentText(albumvergleich);
            trackbox->setCurrentText(titelvergleich);
            genrebox->setCurrentText(genrevergleich);
            yearbox->setValue(jahrvergleich);
            tracknumberbox->setValue(nummervergleich);
            eingabenfreigebenmulti();
        }
        else
        {
            listboxholen();
            rescan=FALSE;
            infozeile->message(i18n("Files do not exist anymore. Rescanning directory."));
        }
    }
    connect(artistbox,SIGNAL(textChanged(const QString &)),SLOT(artistChanged()));
    connect(albumbox,SIGNAL(textChanged(const QString &)),SLOT(albumChanged()));
    connect(trackbox,SIGNAL(textChanged(const QString &)),SLOT(trackChanged()));
    connect(tracknumberbox,SIGNAL(valueChanged(int)),this,SLOT(tracknumberChanged(int)));
    connect(yearbox,SIGNAL(valueChanged(int)),this,SLOT(yearChanged()));
    connect(genrebox,SIGNAL(textChanged(const QString &)),SLOT(genreChanged()));
    disconnect(auswahlbaum,SIGNAL(mousereleased()),this,SLOT(multitagupdate()));
    //disconnect(auswahlbaum,SIGNAL(selectionChanged()),this,SLOT(multitagupdate()));
    //connect(auswahlbaum,SIGNAL(clicked(QListViewItem *)),this,SLOT(multitagupdate()));
}

void tagdialog::rekursivtag(QListViewItem *verzeichnis)
{
    if (static_cast<fileselectoritem *>(verzeichnis)->
            isdirectory)
    {
        QListViewItem *puffer=(verzeichnis->firstChild());
        if (puffer)
        {
            puffer->setSelected(TRUE);
            if (static_cast<fileselectoritem *>(puffer)->
                    isdirectory)
            {
                rekursivtag(puffer);//next recursionstep
            }
            while (puffer=static_cast <fileselectoritem *>
                          (puffer->nextSibling()))
            {
                puffer->setSelected(TRUE);
                if (static_cast<fileselectoritem *>(puffer)->
                        isdirectory)
                {
                    rekursivtag(puffer);//next recursionstep
                }
            };
        }
    }
}

void tagdialog::changeselectedtags()
{
    if (itemcounter)
    {
        tagschanged=TRUE;
        if (singleselect)
        {
            //catch pointer to first file
            fileselectoritem *actualfile=static_cast<fileselectoritem *>(auswahlliste.first());
            actualfile->taginfo.artist=artistbox->currentText();
            actualfile->taginfo.album=albumbox->currentText();
            actualfile->taginfo.title=trackbox->currentText();
            actualfile->taginfo.genre=genrebox->currentText();
            actualfile->taginfo.number=tracknumberbox->value();
            actualfile->taginfo.year=yearbox->value();
            actualfile->taginfo.cdcover=frontcover;
            actualfile->tagchanged=TRUE;
            auswahlbaum->setedited(actualfile);
        }
        else
        {
            QPtrList<QListViewItem>::Iterator index = this->auswahlliste.begin();
            while( index != this->auswahlliste.end())
            {
                kapp->processEvents();
                fileselectoritem *actualfile=static_cast<fileselectoritem *>(*index);
                if (gruppegroupbox->isChecked())
                {
                    actualfile->taginfo.artist=artistbox->currentText();
                    actualfile->tagchanged=TRUE;
                }
                if (albumgroupbox->isChecked())
                {
                    actualfile->taginfo.album=albumbox->currentText();
                    actualfile->tagchanged=TRUE;
                }
                if (titelgroupbox->isChecked())
                {
                    actualfile->taginfo.title=trackbox->currentText();
                    actualfile->taginfo.number=tracknumberbox->value();
                    actualfile->tagchanged=TRUE;
                }
                if (genregroupbox->isChecked())
                {
                    actualfile->taginfo.genre=genrebox->currentText();
                    actualfile->tagchanged=TRUE;
                }
                if (jahrgroupbox->isChecked())
                {
                    actualfile->taginfo.year=yearbox->value();
                    actualfile->tagchanged=TRUE;
                }
                if (covergroupbox->isChecked())
                {
                    actualfile->taginfo.cdcover=frontcover;
                    actualfile->tagchanged=TRUE;
                }
                if (actualfile->tagchanged)
                    auswahlbaum->setedited(actualfile);
                index++;
            }
        }
    }

}

void tagdialog::tagschreiben()
{
    if (itemcounter)
    {
        if (singleselect)
        {
            fileselectoritem *actualfile=static_cast<fileselectoritem *>(auswahlliste.first());
            mediatag Song;
            Song=actualfile->taginfo;
            mediafile file(actualfile->itemfilename);
            if (!file.readsuccess)
            {
                QMessageBox::warning(this,i18n("write error"),i18n("file could not be opened for writing"),"&Ok",QString::null,QString::null,1);
            }
            else
            {
                file.setTags(Song);
                if(file.saveFile())
                {
                    if (settingsfile.verbose)
                    {
                        QMessageBox::information(this,i18n("Transaction report"),i18n("file  ")+actualfile->itemfilename+i18n(" was written successfully"));
                    }
                    auswahlbaum->setsaved(actualfile);
                    if(settingsfile.databasetype)
                        database->updatetag(&Song,aktuelledatei);
                }
                else
                {
                    QMessageBox::warning(this,i18n("write error"),i18n("file could not be opened for writing"),"&Ok",QString::null,QString::null,1);
                }
            }
        }
        else
        {
            progressmainwindow *progresswindow=new progressmainwindow(FALSE);
            progresswindow->show();
            progresswithbar *writestatus=progresswindow->startProgress( i18n("saving edited files"),itemcounter);
            fileselectoritem *actualfile;
            bool abbruch=FALSE;
            long fehler=0;
            long counter=0;
            QPtrList<QListViewItem>::Iterator index = this->auswahlliste.begin();
            while( index != this->auswahlliste.end()&&!abbruch)
            {
                actualfile=static_cast<fileselectoritem *>(*index);
                writestatus->setProgress(++counter);
                if (writestatus->iscancelled||abbruch)
                {
                    abbruch=TRUE;
                }
                mediafile file(actualfile->itemfilename);
                if (file.readsuccess)
                {
                    file.readTags();
                    file.setTags(actualfile->taginfo);
                    if (!file.saveFile())
                    {
                        if (QMessageBox::warning(this,i18n("write error"),i18n("file could not be written"),"&Ok",i18n("&Cancel"),QString::null,1))
                            abbruch=TRUE;
                        fehler++;
                    }
                    else
                    {
                        auswahlbaum->setsaved(actualfile);
                        if(settingsfile.databasetype)
                            database->updatetag(&actualfile->taginfo,actualfile->itemfilename);
                    }
                }
                else
                {
                    if (QMessageBox::warning(this,i18n("write error"),i18n("file does not exist anymore"),"&Ok",i18n("&Cancel"),QString::null,1))
                        abbruch=TRUE;
                    fehler++;
                }
                index++;
            };
            delete writestatus;
            delete progresswindow;
            if (fehler)
            {
                QMessageBox::information(this,i18n("Transaction report"),i18n("action terminated with ")+QString::number(fehler)+i18n(" errors"),i18n("&Ok"));
            }
            else if(settingsfile.verbose)
            {
                QMessageBox::information(this,i18n("Transaction report"),i18n("action terminated without errors"));
            }
        }
    }
    //Check if the first motheritem still says tagschanged
    fileselectoritem *stillmodifiedcheck=static_cast<fileselectoritem *>(auswahlbaum->firstChild());
    if (!stillmodifiedcheck->tagchanged)
        tagschanged=FALSE;
}

void tagdialog::savemodified()
{
    //Dig through the whole tree, and save all modified files
    //Make a copy of the modifiedlist, before starting
    QPtrList<fileselectoritem> backup=auswahlbaum->modifiedlist;
    QPtrListStdIterator<fileselectoritem> index=backup.begin();
    while(index!=backup.end())
    {
        QString actualfile=(*index)->itemfilename;
        mediafile file(actualfile);
        if (!file.readsuccess)
        {
            QMessageBox::warning(this,i18n("write error"),i18n("file could not be opened for writing"),"&Ok",QString::null,QString::null,1);
        }
        else
        {
            file.setTags((*index)->taginfo);
            if(file.saveFile())
            {
                auswahlbaum->setsaved((*index));
                if(settingsfile.databasetype)
                    database->updatetag(&(*index)->taginfo,actualfile);
            }
            else
            {
                QMessageBox::warning(this,i18n("write error"),i18n("file could not be opened for writing"),"&Ok",QString::null,QString::null,1);
            }
        }
        index++;
    };
    //Check if the first motheritem still says tagschanged
    fileselectoritem *stillmodifiedcheck=static_cast<fileselectoritem *>(auswahlbaum->firstChild());
    if (!stillmodifiedcheck->tagchanged)
        tagschanged=FALSE;
}

void tagdialog::imageDropped(QImage droppedimage)
{
    //Check if we are allowed to get this Image atm
    if (itemcounter&&!nopicture)
    {
        covergroupbox->setChecked(TRUE);
        frontcover=droppedimage;
        QImage scaledcover;
        scaledcover=frontcover;
        scaledcover=scaledcover.smoothScale(150,150,QImage::ScaleMin);
        coverlabel->setPixmap(scaledcover);
        removecoverbutton->setEnabled(TRUE);
        //update all selected tags in memory, and mark them as changed, if something was changed on them
        changeselectedtags();
    }
}

void tagdialog::bildladen()
{
    coverfile=QFileDialog::getOpenFileName(QDir::homeDirPath(),i18n("Picturefiles (*.jpg)"),this,i18n("Load file"),i18n("Please choose picture"));
    if (!coverfile.isEmpty())//User selected an image
    {
        frontcover.load(coverfile);
        QImage scaledcover;
        scaledcover=frontcover;
        scaledcover=scaledcover.smoothScale(150,150,QImage::ScaleMin);
        coverlabel->setPixmap(scaledcover);
        removecoverbutton->setEnabled(TRUE);
        //update all selected tags in memory, and mark them as changed, if something was changed on them
        changeselectedtags();
    }
}

void tagdialog::removecoverslot()
{
    frontcover.resize(0,0);
    coverlabel->setText(i18n("no cover set"));
    removecoverbutton->setEnabled(FALSE);
    //update all selected tags in memory, and mark them as changed, if something was changed on them
    changeselectedtags();
}

void tagdialog::eingabensperren()
{
    artistbox->setEnabled(FALSE);
    albumbox->setEnabled(FALSE);
    trackbox->setEnabled(FALSE);
    genrebox->setEnabled(FALSE);
    tracknumberbox->setEnabled(FALSE);
    yearbox->setEnabled(FALSE);
    loadcoverbutton->setEnabled(FALSE);
    removecoverbutton->setEnabled(FALSE);
    findcoverbutton->setEnabled(FALSE);
    speichernknopf->setEnabled(FALSE);
    cleanupbutton->setEnabled(FALSE);
    gruppegroupbox->setCheckable(FALSE);
    gruppegroupbox->setCheckable(FALSE);
    albumgroupbox->setCheckable(FALSE);
    titelgroupbox->setCheckable(FALSE);
    genregroupbox->setCheckable(FALSE);
    jahrgroupbox->setCheckable(FALSE);
    covergroupbox->setCheckable(FALSE);
    guessbutton->setEnabled(FALSE);
}

void tagdialog::eingabenfreigebensingle()
{
    if (nopicture)
    {
        loadcoverbutton->setEnabled(FALSE);
        findcoverbutton->setEnabled(FALSE);
    }
    else
    {
        loadcoverbutton->setEnabled(TRUE);
        findcoverbutton->setEnabled(TRUE);
    }
    artistbox->setEnabled(TRUE);
    albumbox->setEnabled(TRUE);
    trackbox->setEnabled(TRUE);
    genrebox->setEnabled(TRUE);
    tracknumberbox->setEnabled(TRUE);
    yearbox->setEnabled(TRUE);
    speichernknopf->setText(i18n("Save file"));
    speichernknopf->setEnabled(TRUE);
    cleanupbutton->setText(i18n("Cleanup file"));
    cleanupbutton->setEnabled(TRUE);
    guessbutton->setEnabled(TRUE);
    gruppegroupbox->setCheckable(FALSE);
    albumgroupbox->setCheckable(FALSE);
    titelgroupbox->setCheckable(FALSE);
    genregroupbox->setCheckable(FALSE);
    jahrgroupbox->setCheckable(FALSE);
    covergroupbox->setCheckable(FALSE);
    if (!frontcover.isNull())
        removecoverbutton->setEnabled(TRUE);
}

void tagdialog::eingabenfreigebenmulti()
{
    if (nopicture)
    {
        loadcoverbutton->setEnabled(FALSE);
        findcoverbutton->setEnabled(FALSE);
    }
    else
    {
        loadcoverbutton->setEnabled(TRUE);
        findcoverbutton->setEnabled(TRUE);
    }
    speichernknopf->setText(i18n("Save files"));
    speichernknopf->setEnabled(TRUE);
    cleanupbutton->setText(i18n("Cleanup files"));
    cleanupbutton->setEnabled(TRUE);
    guessbutton->setEnabled(TRUE);
    gruppegroupbox->setCheckable(TRUE);
    albumgroupbox->setCheckable(TRUE);
    titelgroupbox->setCheckable(TRUE);
    genregroupbox->setCheckable(TRUE);
    jahrgroupbox->setCheckable(TRUE);
    artistbox->setEnabled(TRUE);
    albumbox->setEnabled(TRUE);
    trackbox->setEnabled(TRUE);
    genrebox->setEnabled(TRUE);
    tracknumberbox->setEnabled(TRUE);
    yearbox->setEnabled(TRUE);
    gruppegroupbox->setChecked(!bandabbruch);
    albumgroupbox->setChecked(!albumabbruch);
    titelgroupbox->setChecked(!titelabbruch&&!nummerabbruch);
    genregroupbox->setChecked(!genreabbruch);
    jahrgroupbox->setChecked(!jahrabbruch);
    covergroupbox->setCheckable(TRUE);
    if (!frontcover.isNull())
    {
        removecoverbutton->setEnabled(TRUE);
        covergroupbox->setChecked(TRUE);
    }
    else
        covergroupbox->setChecked(FALSE);
}

void tagdialog::databasechangeslot()
{
    //deactivate all connections to the combos, so they don't realise the change
    disconnect(artistbox,SIGNAL(textChanged(const QString &)),this,SLOT(artistChanged()));
    disconnect(albumbox,SIGNAL(textChanged(const QString &)),this,SLOT(albumChanged()));
    disconnect(trackbox,SIGNAL(textChanged(const QString &)),this,SLOT(trackChanged()));
    disconnect(genrebox,SIGNAL(textChanged(const QString &)),this,SLOT(genreChanged()));
    boxenholen();
    //reactivate all slots
    connect(artistbox,SIGNAL(textChanged(const QString &)),SLOT(artistChanged()));
    connect(albumbox,SIGNAL(textChanged(const QString &)),SLOT(albumChanged()));
    connect(trackbox,SIGNAL(textChanged(const QString &)),SLOT(trackChanged()));
    connect(genrebox,SIGNAL(textChanged(const QString &)),SLOT(genreChanged()));
}

void tagdialog::boxenholen()
{
    if (settingsfile.databasetype)
    {
        database->fillCombo(artistbox,"artists","artistname");
        database->fillCombo(albumbox,"albums","albumname");
        database->fillCombo(genrebox,"genres","genrename");
        database->fillCombo(trackbox,"tracks","trackname");
    }
    else
    {
        //only clear boxes, and put back old values
        QString oldartist=artistbox->currentText();
        QString oldalbum=albumbox->currentText();
        QString oldtrack=trackbox->currentText();
        QString oldgenre=genrebox->currentText();
        artistbox->clear();
        albumbox->clear();
        trackbox->clear();
        genrebox->clear();
        artistbox->setCurrentText(oldartist);
        albumbox->setCurrentText(oldalbum);
        trackbox->setCurrentText(oldtrack);
        genrebox->setCurrentText(oldgenre);
    }
}

void tagdialog::cleanupslot()
{
    //copy all selected filenames into StringList,and give that StringList to cleanuproutine
    int result=0;
    bool stop=FALSE;
    while(tagschanged&&!result)
    {
        if (!(result=QMessageBox::warning(0,i18n("Save files"),i18n("Some files have edited tags. Do want to save your files first?"),"Save first",i18n("Continue"),i18n("cancel"),1)))
            savemodified();
        else if(result==1||result==2)
            stop=TRUE;
    }
    if ((result==1)||(result==0&&!tagschanged))
    {
        QStringList *selectedFiles=new QStringList;
        QString actualfile;
        QListViewItem *pathbuffer;
        QPtrList<QListViewItem>::Iterator index = this->auswahlliste.begin();
        while( index != this->auswahlliste.end())
        {
            pathbuffer=*index;
            if (!(static_cast<fileselectoritem *>(pathbuffer)->isdirectory)
               )
            {
                actualfile=static_cast<fileselectoritem *>(pathbuffer)->itemfilename;
                selectedFiles->append(actualfile);
            }
            index++;
        }
        cleanup *filemove=new cleanup(this);
        if (filemove->filterok&&filemove->directoriesok)
        {
            filemove->cleanupdir(selectedFiles,itemcounter);
            delete filemove;
        }
        else
            delete filemove;
        if (settingsfile.remove)
        {
            //do a rescan, if files where moved, and deactivate mysql in the meanwhile
            bool mysqlflag=settingsfile.databasetype;
            settingsfile.databasetype=FALSE;
            listboxholen();
            settingsfile.databasetype=mysqlflag;
        }
        delete selectedFiles;
    }
}

void tagdialog::guessslot()
{
    progressmainwindow *progresswindow=new progressmainwindow(FALSE);
    progresswindow->show();
    progressinfoonly *guessstatus=progresswindow->startInfoOnly(i18n("Guessing all selected files"));
    QPtrList<QListViewItem>::Iterator index = this->auswahlliste.begin();
    QListViewItem *pathbuffer;
    //Only make one instance of tagguesser, so we can set defaultfilter
    tagguesser *testguess=new tagguesser(auswahlbaum);
    bool userabort=FALSE;
    while( index != this->auswahlliste.end()&&!userabort)
    {
        pathbuffer=*index;
        QString shownname=static_cast<fileselectoritem *>(pathbuffer)->itemfilename;
        shownname=shownname.right(shownname.length()-(shownname.findRev("/")+1));
        guessstatus->setText(QString(i18n("Guessing file  %1")).arg(shownname));
        if (!(static_cast<fileselectoritem *>(pathbuffer)->isdirectory)
           )
        {
            if(!testguess->checkfile(static_cast<fileselectoritem *>(pathbuffer)))
                userabort=TRUE;
        }
        index++;
    }
    if (testguess->changedtags)
        tagschanged=TRUE;
    delete testguess;
    delete guessstatus;
    delete progresswindow;
    //update the shown tags
    if (!userabort)
        multitagupdate();
}

void tagdialog::artistChanged()
{
    if (settingsfile.databasetype)
    {
        disconnect(artistbox,SIGNAL(textChanged(const QString &)),this,SLOT(artistChanged()));
        disconnect(albumbox,SIGNAL(textChanged(const QString &)),this,SLOT(albumChanged()));
        disconnect(trackbox,SIGNAL(textChanged(const QString &)),this,SLOT(trackChanged()));
        disconnect(genrebox,SIGNAL(textChanged(const QString &)),this,SLOT(genreChanged()));
        //Read in all Combos, and build a sql-query with them
        QString artist=artistbox->currentText();
        QString album=albumbox->currentText();
        QString genre=genrebox->currentText();
        long artistid=database->translateartist(artist);
        if (!artistid)
        {
            //if no artist with that name in database,reread all boxes
            database->fillCombo(artistbox,"artists","artistname");
            database->fillCombo(albumbox,"albums","albumname");
            database->fillCombo(genrebox,"genres","genrename");
        }
        else
        {
            long albumid=database->translatealbum(album);
            //long genreid=database->translategenre(genre);
            QString querystring=QString("artist_id=\"%1\"").arg(artistid);
            database->fillSortedCombo(albumbox,"albums",querystring,"albumname");
            database->fillSortedCombo(genrebox,"tracks",querystring,"genre_id","genres");
            //refetch albumcombo
            album=albumbox->currentText();
            albumid=database->translatealbum(album);
            //Check if a right combination is in the comboboxes, and than modify all songledits
            if(artistid&&albumid)
            {
                querystring=QString("artist_id=\"%1\" AND album_id=\"%2\"").arg(QString::number(artistid),QString::number(albumid));
                database->fillSortedCombo(trackbox,"tracks",querystring,"trackname");
                long year=database->getyear(albumid);
                yearbox->setValue(year);
                //look for tracknumber, and than insert the right track
                int tracknumber=tracknumberbox->value();
                if (tracknumber)
                    database->gettrack(trackbox,artistid,albumid,tracknumber);
            }
            else
            {
                querystring=QString("artist_id=\"%1\"").arg(artistid);
                database->fillSortedCombo(trackbox,"tracks",querystring,"trackname");
            }
        }
        //reactivate all slots
        connect(artistbox,SIGNAL(textChanged(const QString &)),SLOT(artistChanged()));
        connect(albumbox,SIGNAL(textChanged(const QString &)),SLOT(albumChanged()));
        connect(trackbox,SIGNAL(textChanged(const QString &)),SLOT(trackChanged()));
        connect(genrebox,SIGNAL(textChanged(const QString &)),SLOT(genreChanged()));
        connect(tracknumberbox,SIGNAL(valueChanged(int)),SLOT(tracknumberChanged(int)));
    }
    //update all selected tags in memory, and mark them as changed, if something was changed on them
    changeselectedtags();
}

void tagdialog::albumChanged()
{
    if (settingsfile.databasetype)
    {
        //deactivate all other comboslots,to stop recursion
        disconnect(artistbox,SIGNAL(textChanged(const QString &)),this,SLOT(artistChanged()));
        disconnect(albumbox,SIGNAL(textChanged(const QString &)),this,SLOT(albumChanged()));
        disconnect(trackbox,SIGNAL(textChanged(const QString &)),this,SLOT(trackChanged()));
        disconnect(genrebox,SIGNAL(textChanged(const QString &)),this,SLOT(genreChanged()));
        //Read in all Combos, and build a sql-query with them
        QString artist=artistbox->currentText();
        QString album=albumbox->currentText();
        QString genre=genrebox->currentText();
        long albumid=database->translatealbum(album);
        if (!albumid)
        {
            //if no album with that name in database,reread all boxes
            database->fillCombo(artistbox,"artists","artistname");
            database->fillCombo(albumbox,"albums","albumname");
            database->fillCombo(genrebox,"genres","genrename");
        }
        else
        {
            long artistid=database->translateartist(artist);
            //long genreid=database->translategenre(genre);
            QString querystring=QString("album_id=\"%1\"").arg(albumid);
            database->fillSortedCombo(artistbox,"tracks",querystring,"artist_id","artists");
            database->fillSortedCombo(genrebox,"tracks",querystring,"genre_id","genres");
            //refetch albumcombo
            artist=artistbox->currentText();
            artistid=database->translateartist(artist);
            //Check if a right combination is in the comboboxes, and than modify all songledits
            if(artistid&&albumid)
            {
                querystring=QString("artist_id=\"%1\" AND album_id=\"%2\"").arg(QString::number(artistid),QString::number(albumid));
                database->fillSortedCombo(trackbox,"tracks",querystring,"trackname");
                long year=database->getyear(albumid);
                yearbox->setValue(year);
                //look for tracknumber, and than insert the right track
                int tracknumber=tracknumberbox->value();
                if (tracknumber)
                    database->gettrack(trackbox,artistid,albumid,tracknumber);
            }
            else
            {
                querystring=QString("album_id=\"%1\"").arg(albumid);
                database->fillSortedCombo(trackbox,"tracks",querystring,"trackname");
            }
        }
        //reactivate all slots
        connect(artistbox,SIGNAL(textChanged(const QString &)),SLOT(artistChanged()));
        connect(albumbox,SIGNAL(textChanged(const QString &)),SLOT(albumChanged()));
        connect(trackbox,SIGNAL(textChanged(const QString &)),SLOT(trackChanged()));
        connect(genrebox,SIGNAL(textChanged(const QString &)),SLOT(genreChanged()));
    }
    //update all selected tags in memory, and mark them as changed, if something was changed on them
    changeselectedtags();
}

void tagdialog::genreChanged()
{
    if (settingsfile.databasetype)
    {
        //deactivate all other comboslots,to stop recursion
        disconnect(artistbox,SIGNAL(textChanged(const QString &)),this,SLOT(artistChanged()));
        disconnect(albumbox,SIGNAL(textChanged(const QString &)),this,SLOT(albumChanged()));
        disconnect(trackbox,SIGNAL(textChanged(const QString &)),this,SLOT(trackChanged()));
        disconnect(genrebox,SIGNAL(textChanged(const QString &)),this,SLOT(genreChanged()));
        //Read in all Combos, and build a sql-query with them
        QString artist=artistbox->currentText();
        QString album=albumbox->currentText();
        QString genre=genrebox->currentText();
        long genreid=database->translategenre(genre);
        if (!genreid)
        {
            //if no album with that name in database,reread all boxes
            database->fillCombo(artistbox,"artists","artistname");
            database->fillCombo(albumbox,"albums","albumname");
            database->fillCombo(genrebox,"genres","genrename");
        }
        else
        {
            long artistid=database->translateartist(artist);
            long albumid=database->translatealbum(album);
            QString querystring=QString("genre_id=\"%1\"").arg(genreid);
            database->fillSortedCombo(artistbox,"tracks",querystring,"artist_id","artists");
            database->fillSortedCombo(albumbox,"tracks",querystring,"album_id","albums");
            //refetch albumcombo and artistcombo
            album=albumbox->currentText();
            albumid=database->translatealbum(album);
            artist=artistbox->currentText();
            artistid=database->translateartist(artist);
            //Check if a right combination is in the comboboxes, and than modify all songledits
            if(artistid&&albumid)
            {
                querystring=QString("artist_id=\"%1\" AND album_id=\"%2\"").arg(QString::number(artistid),QString::number(albumid));
                database->fillSortedCombo(trackbox,"tracks",querystring,"trackname");
                long year=database->getyear(albumid);
                yearbox->setValue(year);
                //look for tracknumber, and than insert the right track
                int tracknumber=tracknumberbox->value();
                if (tracknumber)
                    database->gettrack(trackbox,artistid,albumid,tracknumber);
            }
            else
            {
                querystring=QString("album_id=\"%1\"").arg(albumid);
                database->fillSortedCombo(trackbox,"tracks",querystring,"trackname");
            }
        }
        //reactivate all slots
        connect(artistbox,SIGNAL(textChanged(const QString &)),SLOT(artistChanged()));
        connect(albumbox,SIGNAL(textChanged(const QString &)),SLOT(albumChanged()));
        connect(trackbox,SIGNAL(textChanged(const QString &)),SLOT(trackChanged()));
        connect(genrebox,SIGNAL(textChanged(const QString &)),SLOT(genreChanged()));
    }
    //update all selected tags in memory, and mark them as changed, if something was changed on them
    changeselectedtags();
}

void tagdialog::trackChanged()
{
    if (settingsfile.databasetype)
    {
        disconnect(artistbox,SIGNAL(textChanged(const QString &)),this,SLOT(artistChanged()));
        disconnect(albumbox,SIGNAL(textChanged(const QString &)),this,SLOT(albumChanged()));
        disconnect(trackbox,SIGNAL(textChanged(const QString &)),this,SLOT(trackChanged()));
        disconnect(genrebox,SIGNAL(textChanged(const QString &)),this,SLOT(genreChanged()));
        //Read in all Combos, and build a sql-query with them
        QString artist=artistbox->currentText();
        QString album=albumbox->currentText();
        QString genre=genrebox->currentText();
        QString track=trackbox->currentText();
        /*      long genreid=database->translategenre(genre);
        long artistid=database->translateartist(artist);
        long albumid=database->translatealbum(album);*/
        QString querystring=QString("trackname=\"%1\"").arg(track);
        database->fillSortedCombo(artistbox,"tracks",querystring,"artist_id","artists");
        database->fillSortedCombo(albumbox,"tracks",querystring,"album_id","albums");
        database->fillSortedCombo(genrebox,"tracks",querystring,"genre_id","genres");
        //update all selected tags in memory, and mark them as changed, if something was changed on them
        //reactivate all slots
        connect(artistbox,SIGNAL(textChanged(const QString &)),SLOT(artistChanged()));
        connect(albumbox,SIGNAL(textChanged(const QString &)),SLOT(albumChanged()));
        connect(trackbox,SIGNAL(textChanged(const QString &)),SLOT(trackChanged()));
        connect(genrebox,SIGNAL(textChanged(const QString &)),SLOT(genreChanged()));
    }
    changeselectedtags();
}

void tagdialog::tracknumberChanged(int tracknumber)
{
    if (settingsfile.databasetype)
    {
        disconnect(trackbox,SIGNAL(textChanged(const QString &)),this,SLOT(trackChanged()));
        QString artist=artistbox->currentText();
        QString album=albumbox->currentText();
        QString querystring;
        long artistid=database->translateartist(artist);
        long albumid=database->translatealbum(album);
        if(artistid&&albumid)
        {
            querystring=QString("artist_id=\"%1\" AND album_id=\"%2\"").arg(QString::number(artistid),QString::number(albumid));
            database->fillSortedCombo(trackbox,"tracks",querystring,"trackname");
            long year=database->getyear(albumid);
            yearbox->setValue(year);
            //look for tracknumber, and than insert the right track
            if (tracknumber)
                database->gettrack(trackbox,artistid,albumid,tracknumber);
        }
        else
        {
            querystring=QString("album_id=\"%1\"").arg(albumid);
            database->fillSortedCombo(trackbox,"tracks",querystring,"trackname");
        }
        //update all selected tags in memory, and mark them as changed, if something was changed on them
        connect(trackbox,SIGNAL(textChanged(const QString &)),SLOT(trackChanged()));
    }
    changeselectedtags();
}

void tagdialog::yearChanged()
{
    //update all selected tags in memory, and mark them as changed, if something was changed on them
    changeselectedtags();
}

void tagdialog::dirchange(QListViewItem *selecteditem)
{
    //disconnect(auswahlbaum,SIGNAL(selectionChanged()),this,SLOT(multitagupdate()));
    settingsfile.reading_dir=static_cast<fileselectoritem *>(selecteditem)->itemfilename;
    listboxholen();
    //connect(auswahlbaum,SIGNAL(selectionChanged()),this,SLOT(multitagupdate()));
}

void tagdialog::showcontext(QListViewItem *selecteditem,const QPoint &position)
{
    //Throw away old contextmenu
    taggercontext->clear();
    //Load the right menu, and set the right switch, so we know what we need to do
    if (selecteditem)
    {
        if (static_cast<fileselectoritem *>(selecteditem)->
                isdirectory)
            taggercontext->dirmenu(selecteditem);
        else
            taggercontext->filemenu(selecteditem);
    }
    else
        taggercontext->nonselectedmenu();
    //connect all signals of the contextmenu
    taggercontext->popup(position);
}

void tagdialog::checkmousebutton(int button,QListViewItem *selected)
{
    if (button==1&&selected)
    {
        connect(auswahlbaum,SIGNAL(mousereleased()),this,SLOT(multitagupdate()));
    }
}

void tagdialog::findcoverslot()
{
    //Create a findstring, out of the already found tags
    if (!(artistbox->currentText().length()==0)||!(albumbox->currentText().length()==0))
    {
        QString findstring=QString("%1+%2").arg(artistbox->currentText(),albumbox->currentText());
        findstring=findstring.replace(' ','+');
        coverdialog=new coverfinder2(findstring);
        coverdialog->show();
        connect (coverdialog,SIGNAL(pictureselected(QImage)),SLOT(coverupdate(QImage)));
        connect (coverdialog,SIGNAL(abort()),SLOT(coverabort()));
    }
    else
        QMessageBox::information(0,i18n("Missing information"),i18n("No values to search for!"),QMessageBox::Ok);
}

void tagdialog::coverabort()
{
    delete coverdialog;
    coverdialog=NULL;
}

void tagdialog::coverupdate(QImage newcover)
{
    if (coverdialog)
    {
        delete coverdialog;
        coverdialog=NULL;
    }
    covergroupbox->setChecked(TRUE);
    frontcover=newcover;
    QImage scaledcover;
    scaledcover=frontcover;
    scaledcover=scaledcover.smoothScale(150,150,QImage::ScaleMin);
    coverlabel->setPixmap(scaledcover);
    removecoverbutton->setEnabled(TRUE);
    //update all selected tags in memory, and mark them as changed, if something was changed on them
    changeselectedtags();
}

void tagdialog::appendsongslot()
{
    //Fetch list of selected files
    getselectionlist();
    //Give the list to a playerroutine
    //aktuelledatei=static_cast<fileselectoritem *>(inhalt)->itemfilename;
    if (auswahlliste.first())
    {
        QString songtoadd=static_cast<fileselectoritem *>(auswahlliste.first())->itemfilename;
        playerlink->addTrack(songtoadd);
    }
}

void tagdialog::deleteslot()
{
    //Fetch list of selected files
    cerr<<"deleteslot"<<endl;
    //getselectionlist();
    auswahlliste.first();
    while (auswahlliste.current())
    {
        QString songtoadd=static_cast<fileselectoritem *>(auswahlliste.current())->itemfilename;

        cerr<<"delete dir  "<<songtoadd<<endl;
        auswahlliste.next();
    }
}

void tagdialog::startnewsongslot()
{
    //Fetch list of selected files
    getselectionlist();
    //Give the list to a playerroutine
    //aktuelledatei=static_cast<fileselectoritem *>(inhalt)->itemfilename;
    if (auswahlliste.first())
    {
        fileselectoritem *songtoadd=static_cast<fileselectoritem *>(auswahlliste.current());
        if(playerlink->createList(songtoadd->itemfilename))
        {
            auswahlliste.next();
            bool error=FALSE;
            while(auswahlliste.current()&&!error)
            {
                songtoadd=static_cast<fileselectoritem *>(auswahlliste.current());
                if(!playerlink->addTrack(songtoadd->itemfilename))
                    error=TRUE;
                auswahlliste.next();
            }
        }
    }
    else
    {
        QMessageBox::information(0,i18n("Play files"),i18n("There are no playable files in your selection!"),QMessageBox::Ok);
    }
}

void tagdialog::renamefileslot()
{
    //Fetch list of selected files
    getselectionlist();
    cerr<<"rename files"<<endl;

}

//Slots for the flexiblecontextmenu

flexiblecontext::flexiblecontext(tagdialog *pointer,const QString text)
{
    currentobject=NULL;
    parent=pointer;
}

flexiblecontext::~flexiblecontext()
{}

void flexiblecontext::filemenu(QListViewItem *selecteditem)
{
    //It is important, that we make an multitagupdate, otherwise we have no selected files.
    parent->getselectionlist();
    currentobject=selecteditem;
    //set up a filemenu
    //check if we have a valid player selected
    if (settingsfile.playertype==0)//only mplayer atm
    {
        insertItem(i18n("Play Song(s)"),parent,SLOT(startnewsongslot()));
        if (playerlink->isplaying)
        {
            insertItem(i18n("Append Song(s) on list"),parent,SLOT(appendsongslot()));
        }
    }
    insertItem(i18n("Guess tags"),parent,SLOT(guessslot()));
    insertItem(i18n("Cleanup"),parent,SLOT(cleanupslot()));
    //insertItem(i18n("Rename file"),parent,SLOT(renamefileslot()));
    //insertItem(i18n("Delete file"),parent,SLOT(deleteslot()));
}

void flexiblecontext::dirmenu(QListViewItem *selecteditem)
{
    //It is important, that we make an multitagupdate, otherwise we have no selected files.
    parent->getselectionlist();
    currentobject=selecteditem;
    //set up a filemenu
    if (settingsfile.playertype==0)//only mplayer atm
    {
        insertItem(i18n("Play Song(s)"),parent,SLOT(startnewsongslot()));
        if (playerlink->isplaying)
        {
            insertItem(i18n("Append Song(s) on list"),parent,SLOT(appendsongslot()));
        }
    }
    insertItem(i18n("Guess tags"),parent,SLOT(guessslot()));
    insertItem(i18n("Cleanup"),parent,SLOT(cleanupslot()));
    insertItem(i18n("Set as new readingdirectory"),this,SLOT(setdir()));
    //connect(this,SIGNAL(activated(int)),SLOT(setdir(int)));
    if (settingsfile.reading_dir.contains("/")>1)
        insertItem(i18n("Directory up"),this,SLOT(dirup()));
    //insertItem(i18n("Delete directory"),parent,SLOT(deleteslot()));
    //insertItem(i18n("Rename directory"),this,SLOT(renamedir()));
}

void flexiblecontext::nonselectedmenu()
{
    currentobject=NULL;
    insertItem(i18n("Rescan actual directoy"),this,SLOT(setdir()));
    if (settingsfile.reading_dir.contains("/")>1)
        insertItem(i18n("Directory up"),this,SLOT(dirup()));
}

void flexiblecontext::setdir()
{
    if(currentobject)
        settingsfile.reading_dir=static_cast<fileselectoritem *>(currentobject)->itemfilename;
    emit readnewdir();
}

void flexiblecontext::dirup()
{
    if (settingsfile.reading_dir.contains("/")>=1)
    {
        settingsfile.reading_dir=settingsfile.reading_dir.left(settingsfile.reading_dir.findRev("/"));
    QFileInfo checkdir(settingsfile.reading_dir);
    if(checkdir.exists()&&checkdir.isDir())
        {
        emit readnewdir();
        }
    else
    {
        QMessageBox::warning(0,i18n("Fileselector-error"),i18n("The new reading dir does not exist. Setting your home-directory as new reading-directory"),QMessageBox::Ok,0);
        settingsfile.reading_dir=QDir::homeDirPath();
        emit readnewdir();
    }
    }
}


void flexiblecontext::renamedir()
{
    cerr<<"rename dir"<<endl;
}
