/***************************************************************************
 *   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.             *
 ***************************************************************************/

#include "mysqlinterface.h"

mysqldatabase::mysqldatabase()
{
    quit=FALSE;
    oldmodelchecked=FALSE;
    databaseconnect=QSqlDatabase::addDatabase(DRIVER);
    //Überprüfen, ob Datenbank schon besteht.
    databaseconnect->setDatabaseName(DATABASE);
    databaseconnect->setUserName(USER);
    databaseconnect->setPassword(PASSWORD);
    databaseconnect->setHostName(HOST);
    passbox=NULL;
    while(!databaseconnect->open()&&(!this->quit))//Check wether the database is opening or not
    {
        //Check if an old kmp3organizer database exists
        if(!oldmodelchecked)
        {
            cerr<<"trying to open old database"<<endl;
            databaseconnect->setDatabaseName(OLDDATABASE);
            databaseconnect->setUserName(OLDUSER);
            databaseconnect->setPassword(OLDPASSWORD);
            databaseconnect->setHostName(HOST);
            if(databaseconnect->open())
            {
                //old database exists
                //ask user,wether to import,or delete the old database
                if (!(QMessageBox::warning(0,i18n("Import old Database"),i18n("There is an old K-Yamo-Database existing.<br>Do you want to import, or delete it?"),"Delete",i18n("Import"),QString::null,1)))
                {
                    //create new database, than delete old one
                    databaseconnect->close();
                    createnewdb();
                    databaseconnect->setDatabaseName("mysql");
                    databaseconnect->setUserName(rootuser);
                    databaseconnect->setPassword(rootpass);
                    databaseconnect->setHostName("localhost");
                    if (databaseconnect->open())
                    {
                        QSqlQuery querystatement;
                        querystatement.exec ("drop database "OLDDATABASE";");
                        databaseconnect->close();
                    }
                    oldmodelchecked=TRUE;
                }
                else
                {
                    //create new database, than import old database into the new one
                    databaseconnect->close();
                    if (createnewdb())
                    {
                        //Import old database
                        if (importolddb())
                        {
                            oldmodelchecked=TRUE;
                            databaseconnect->setDatabaseName("mysql");
                            databaseconnect->setUserName(rootuser);
                            databaseconnect->setPassword(rootpass);
                            databaseconnect->setHostName("localhost");
                            if (databaseconnect->open())
                            {
                                QSqlQuery querystatement;
                                //If import was successfull, delete old database
                                querystatement.exec ("drop database "OLDDATABASE";");
                            }
                        }
                    }
                }
            }
            else
                oldmodelchecked=TRUE;
        }
        else
        {
            cout<<"No old database found"<<endl;
            createnewdb();
        }
        //set standard-connectionoptions, before next retry
        databaseconnect->setDatabaseName(DATABASE);
        databaseconnect->setUserName(USER);
        databaseconnect->setPassword(PASSWORD);
    }
    if(!this->quit)
    {
        //Check for all tables, and generate the missing ones, if quit is not set.
        if (!(databaseconnect->tables().contains("artists")))
            generateArtisttable();
        if (!(databaseconnect->tables().contains("albums")))
            generateAlbumtable();
        if (!(databaseconnect->tables().contains("genres")))
            generateGenretable();
        if (!(databaseconnect->tables().contains("tracks")))
            generateTracktable();
        if (!(databaseconnect->tables().contains("files")))
            generateFiletable();

    }
}

mysqldatabase::~mysqldatabase()
{
    cerr<<"mysql destructor"<<endl;
    if (databaseconnect->isOpen())
        databaseconnect->close();
}

void mysqldatabase::fetchacountdata(QString user,QString pass)
{
    rootuser=user;
    rootpass=pass;
}

void mysqldatabase::abort()
{
    if (!(QMessageBox::warning(0,i18n("cancel"),i18n("Without MySQL the helper-database can not be used.<br><br>use K-Yamo without MYSQL or retry login?"),"&without MySQL",i18n("&try again"),QString::null,1)))
    {
        this->quit=TRUE;
    }

}

bool mysqldatabase::createnewdb()
{
    //Get accountdata for mysql from user, and create database with that accountdata
    if (!passbox)
        passbox=new passwordbox();
    connect (passbox,SIGNAL(success(QString, QString )),this,SLOT(fetchacountdata(QString,QString)));
    connect (passbox,SIGNAL(abort()),this,SLOT(abort()));
    passbox->exec();
    databaseconnect->setDatabaseName("mysql");
    databaseconnect->setUserName(rootuser);
    databaseconnect->setPassword(rootpass);
    databaseconnect->setHostName("localhost");
    if (databaseconnect->open())
    {
        QSqlQuery querystatement;
        querystatement.exec ("create database "DATABASE"");
        querystatement.exec("use "DATABASE"");
        //create all needed tables
        //create artiststable, if it doesn't exist already
        if (!(databaseconnect->tables().contains("artists")))
            generateArtisttable();
        //create albumstable, if it doesn't exist already
        if (!(databaseconnect->tables().contains("albums")))
            generateAlbumtable();
        //create genrestable, if it doesn't exist already
        if (!(databaseconnect->tables().contains("genres")))
            generateGenretable();
        //create trackstable, if it doesn't exist already
        if (!(databaseconnect->tables().contains("tracks")))
            generateTracktable();
        //create filetable,if it isn't existing already
        if (!(databaseconnect->tables().contains("files")))
            generateFiletable();
        //set new loginaccount for the new database
        querystatement.exec("GRANT ALL PRIVILEGES ON "DATABASE".* TO "USER"@"HOST" IDENTIFIED BY \""PASSWORD"\"");
        querystatement.exec("FLUSH PRIVILEGES");
        //disconnect root-connection with mysql
        databaseconnect->close();
        return TRUE;
    }
    else
        return FALSE;
}

bool mysqldatabase::importolddb()
{
    bool importOk=FALSE;
    databaseconnect->setDatabaseName(OLDDATABASE);
    databaseconnect->setUserName(OLDUSER);
    databaseconnect->setPassword(OLDPASSWORD);
    databaseconnect->setHostName(HOST);
    if(databaseconnect->open())
    {
        //get most information out of old trackstable, than catch releaseyear and the genre out of albumstable
        //store everything in a field of i3tags, than enter the tags into the new database
        QPtrList<mediatag> taglist;
        taglist.setAutoDelete(TRUE);//delete tags, when list is deleted
        mediatag *current;
        QSqlCursor trackstable("tracks");
        trackstable.select();
        long counter=0;
        progressmainwindow *progresswindow=new progressmainwindow(FALSE);
        progresswindow->show();
        progressinfoonly *progress=progresswindow->startInfoOnly(i18n("Reading in old database"));
        while(trackstable.next())
        {
            QString infotext=QString(i18n("Importing tag number %1").arg(QString::number(++counter)));
            progress->setText(infotext);
            current=new mediatag();
            current->album=trackstable.value("albumname").toString();
            current->artist=trackstable.value("groupname").toString();
            current->title=trackstable.value("trackname").toString();
            current->number=trackstable.value("tracknumber").toInt();
            QSqlCursor albumstable("albums");
            QString searchexpression=QString("albumname=\"%1\" AND groupname = \"%2\"").arg(current->album,current->artist);
            albumstable.select(searchexpression);
            albumstable.next();
            current->genre=albumstable.value("genre").toString();

            current->year=albumstable.value("recordedyear").toInt();
            taglist.append(current);
        }
        QPtrList<mediatag>::Iterator index=taglist.begin();
        long newcounter=0;
        progresswindow->killProgress(progress);
        progresswithbar *progress2=progresswindow->startProgress(i18n("Writing new database."),counter);
        //close old database
        databaseconnect->close();
        //open new built database
        databaseconnect->setDatabaseName(DATABASE);
        databaseconnect->setUserName(USER);
        databaseconnect->setPassword(PASSWORD);
        databaseconnect->setHostName(HOST);
        if(databaseconnect->open())//Check wether the database is opening or not
        {
            while (index!=taglist.end()&&!progress2->iscancelled)
            {
                progress2->setProgress(newcounter++);
                current=*index;
                writetag(current);
                index++;
            }
            if (!progress2->iscancelled)
                importOk=TRUE;
            else
            {
                importOk=FALSE;
                //delete new partdatabase
                QSqlQuery querystatement;
                querystatement.exec ("drop database "DATABASE";");
            }
        }
        else
        {
            //Import impossible, cause new database does not open
            importOk=FALSE;
        }
        taglist.clear();
        delete progresswindow;
    }
    else
    {
        //Import impossible,because connection does not work
        importOk=FALSE;
    }
    return importOk;
}

//This function is still present for updating old databases
//There is a newer one, that stores filenames also
void mysqldatabase::writetag(mediatag *Song)
{
    //set all foreign indexes to 0
    long artistindex=0;
    long albumindex=0;
    long genreindex=0;
    long trackindex=0;
    //Fill up tags if not propper set
    if (Song->album.isEmpty())
        Song->album="no album";
    if (Song->title.isEmpty())
        Song->title="no songname";
    if (Song->artist.isEmpty())
        Song->artist="no artist";
    if (Song->genre.isEmpty())
        Song->genre="no genre";

    //###################Check for Artist####################
    QSqlCursor artiststable("artists");
    QString artistsearch=QString("artistname =\"%1\"").arg(Song->artist);
    artiststable.select(artistsearch);
    if(!(artiststable.first()))//If artist doesn't exist, create a db-entry
    {
        QSqlRecord *buffer=artiststable.primeInsert();
        buffer->setValue("artistname",Song->artist.utf8());
        if (!artiststable.insert())
        {
            QSqlError error=artiststable.lastError();
            cerr<<"artisterror:"<<error.text()<<endl;
        }

        //reposition sql-cursor, so we can read out the new id for the artist
        artiststable.select(artistsearch);
        artiststable.first();
    }
    //fetch artisid as foreign key for other tables
    bool ok;
    artistindex=(QString(artiststable.value("artistid").toString())).toLong(&ok,10);

    //###################Check for Album####################
    QSqlCursor albumstable("albums");
    QString albumsearch=QString("albumname =\"%1\" and artist_id=\"%2\"").arg(Song->album,QString::number(artistindex));
    albumstable.select(albumsearch);
    if(!(albumstable.first()))//If album doesn't exist, create a db-entry
    {
        QSqlRecord *buffer=albumstable.primeInsert();
        buffer->setValue("albumname",Song->album.utf8());
        buffer->setValue("artist_id",QString::number(artistindex));
        buffer->setValue("releaseyear",Song->year);
        if (!albumstable.insert())
        {
            QSqlError error=albumstable.lastError();
            cerr<<"albumserror:"<<error.text()<<endl;
        }
        //reposition sql-cursor, so we can read out the new id for the album
        albumstable.select(albumsearch);
        albumstable.first();
    }
    //fetch artisid as foreign key for other tables
    albumindex=(QString(albumstable.value("albumid").toString())).toLong(&ok,10);

    //###################Check for Genre####################
    QSqlCursor genrestable("genres");
    QString genresearch=QString("genrename =\"%1\"").arg(Song->genre);
    genrestable.select(genresearch);
    if(!(genrestable.first()))//If genre doesn't exist, create a db-entry
    {
        QSqlRecord *buffer=genrestable.primeInsert();
        buffer->setValue("genrename",Song->genre.utf8());
        if (!genrestable.insert())
        {
            QSqlError error=genrestable.lastError();
            cerr<<"genreserror: "<<error.text()<<endl;
        }
        //reposition sql-cursor, so we can read out the new id for the album
        genrestable.select(genresearch);
        genrestable.first();
    }
    //fetch artistid as foreign key for other tables
    genreindex=(QString(genrestable.value("genreid").toString())).toLong(&ok,10);

    //###################Check for Song####################

    QSqlCursor trackstable("tracks");
    QString tracksearch=QString("trackname=\"%1\" and album_id=\"%2\" and artist_id=\"%3\"").arg(Song->title,QString::number(albumindex),QString::number(artistindex));
    trackstable.select(tracksearch);
    if(!(trackstable.first()))//If Song doesn't exist, create a db-entry
    {
        QSqlRecord *buffer=trackstable.primeInsert();
        buffer->setValue("album_id",QString::number(albumindex));
        buffer->setValue("artist_id",QString::number(artistindex));
        buffer->setValue("genre_id",QString::number(genreindex));
        buffer->setValue("trackname",Song->title.utf8());
        buffer->setValue("tracknumber",Song->number);
        if(!trackstable.insert())
        {
            QSqlError error=trackstable.lastError();
            cerr<<"trackserror"<<error.text()<<endl;
        }
        //reposition sql-cursor, so we can read out the new id for the track
        trackstable.select(tracksearch);
        trackstable.first();
    }
    trackindex=(QString(trackstable.value("trackid").toString())).toLong(&ok,10);
    //Write the tracknumber, a datestamp and the filename in table for files
    //first check for the last modification date, and generate our string for the table
}

//Functions for filling comboboxes
void mysqldatabase::fillCombo(QComboBox *combobox,QString tablename,QString sortcriteria)
{
    //rescue current Text
    QString rescued=combobox->currentText();
    combobox->clear();
    QString result;
    QSqlCursor searchtable(tablename);
    searchtable.select("",searchtable.index(sortcriteria));
    while(searchtable.next())
    {
        result=QString::fromUtf8(searchtable.value(sortcriteria).toString());
        if (!result.isEmpty())
            combobox->insertItem(result,-1);
    }
    //insert rescued text as currentText
    combobox->setCurrentText(rescued);
}

//Fill given combobox with the results found in the searchedtable
//A sql-querystring is needed for this function
void mysqldatabase::fillSortedCombo(QComboBox *combobox,QString tablename,QString sqlquery,QString criteria)
{
    //fetch old currentText, maybe we need this later again
    QString rescue=combobox->currentText();
    combobox->clear();
    QString result;
    QSqlCursor searchtable(tablename);
    searchtable.select(sqlquery);
    long resultcounter=0;
    while(searchtable.next())
    {
        resultcounter++;
        result=QString::fromUtf8(searchtable.value(criteria).toString());
        if (!result.isEmpty())
            combobox->insertItem(result,-1);
    }
    //put back the old value into the combobox
    combobox->setCurrentText(rescue);
}

//Fill given combobox with results. The resultstrings are out of the realtable
//This function is needed to get real strings, not just te indexnumbers from the tables.
//A sql-querystring is needed for this function
void mysqldatabase::fillSortedCombo(QComboBox *combobox,QString tablename,QString sqlquery,QString criteria,QString realtable)
{
    //fetch old currentText, maybe we need this later again
    QString rescue=combobox->currentText();
    combobox->clear();
    QString result;
    QSqlCursor searchtable(tablename);
    searchtable.select(sqlquery);
    QStringList bufferlist;
    while(searchtable.next())
    {
        result=QString::fromUtf8(searchtable.value(criteria).toString());
        if (!result.isEmpty())
        {
            //get every entry only once
            bool doubleentry=FALSE;
            QStringList::Iterator index=bufferlist.begin();
            while (index!=bufferlist.end())
            {
                if (!QString(*index).compare(result))
                {
                    doubleentry=TRUE;
                    index=bufferlist.end();
                }
                else
                    index++;
            }
            if (!doubleentry)
            {
                bufferlist.append(result);
            }
        }
    }
    //now translate the indexes to real strings
    QStringList::Iterator index=bufferlist.begin();
    QString realquery=criteria.remove("_");
    QString realcriteria=QString("%1%2").arg(criteria.remove("id"),"name");
    long resultcounter=0;
    while (index!=bufferlist.end())
    {
        QString querystring=QString("%1=\"%2\"").arg(realquery,QString(*index));
        resultcounter++;
        QSqlCursor searchtable(realtable);
        searchtable.select(querystring);
        searchtable.first();
        result=searchtable.value(realcriteria).toString();
        combobox->insertItem(result,-1);
        index++;
    }
    //put back the old value in the combobox
    combobox->setCurrentText(rescue);
}

//All translatefunctions just give back an indexnumber for a string
//This is needed, because the tracks table only stores foreign index-numbers for Artist,Album and Genre
//So referntial integrity is given
long mysqldatabase::translateartist(QString artist)
{
    artist=artist.utf8();
    QSqlCursor artiststable("artists");
    QString searchstring=QString("artistname =\"%1\"").arg(artist);
    artiststable.select(searchstring);
    if  (artiststable.first())
    {
        bool ok;
        return QString(artiststable.value("artistid").toString()).toLong(&ok,10);
    }
    else
        return 0;
}

QString mysqldatabase::translateartist(long artistindex)
{
    QSqlCursor artiststable("artists");
    QString artistsearch=QString("artistid =\"%1\"").arg(QString::number(artistindex));
    artiststable.select(artistsearch);
    artiststable.first();
    QString artistname=QString::fromUtf8(artiststable.value("artistname").toString());
    return artistname;
}

long mysqldatabase::translatealbum(QString album)
{
    album=album.utf8();
    QSqlCursor albumstable("albums");
    QString searchstring=QString("albumname =\"%1\"").arg(album);
    albumstable.select(searchstring);
    if  (albumstable.first())
    {
        bool ok;
        return QString(albumstable.value("albumid").toString()).toLong(&ok,10);
    }
    else
        return 0;
}

QString mysqldatabase::translatealbum(long albumindex)
{
    QSqlCursor albumstable("albums");
    QString albumsearch=QString("albumid =\"%1\"").arg(QString::number(albumindex));
    albumstable.select(albumsearch);
    albumstable.first();
    QString albumname=QString::fromUtf8(albumstable.value("albumname").toString());
    return albumname;
}

long mysqldatabase::translategenre(QString genre)
{
    bool ok;
    genre=genre.utf8();
    QSqlCursor genrestable("genres");
    QString searchstring=QString("genrename =\"%1\"").arg(genre);
    genrestable.select(searchstring);
    if  (genrestable.first())
    {
        return QString(genrestable.value("genreid").toString()).toLong(&ok,10);
    }
    else
        return 0;
}

QString mysqldatabase::translategenre(long genreindex)
{
    QSqlCursor genrestable("genres");
    QString genresearch=QString("genreid =\"%1\"").arg(QString::number(genreindex));
    genrestable.select(genresearch);
    genrestable.first();
    QString genrename=QString::fromUtf8(genrestable.value("genrename").toString());
    return genrename;
}

//Check if album exists in database
//fill the given songlist with the containes tracks, if album is found
bool mysqldatabase::albumexists(long artistid,long albumid,QStringList *songlist)
{
    bool albumfound=FALSE;
    QSqlCursor trackstable("tracks");
    QString searchstring=QString("artist_id =\"%1\" AND album_id=\"%2\"").arg(QString::number(artistid),QString::number(albumid));
    trackstable.select(searchstring,trackstable.index("tracknumber"));
    while(trackstable.next())
    {
        albumfound=TRUE;
        QString result=QString::fromUtf8(trackstable.value("trackname").toString());
        songlist->append(result);
    }
    return albumfound;
}

long mysqldatabase::getyear(long albumindex)
{
    long releaseyear=0;
    QSqlCursor albumstable("albums");
    QString searchstring=QString("albumid=\"%1\"").arg(QString::number(albumindex));
    albumstable.select(searchstring);
    if (albumstable.first())
        ;
    {
        bool ok;
        releaseyear=QString(albumstable.value("releaseyear").toString()).toLong(&ok,10);
    }
    return releaseyear;
}

//Set trackbox to song found in database, that matches the given criterias
void mysqldatabase::gettrack(QComboBox *trackbox,long artistid,long albumid,int tracknumber)
{
    QSqlCursor trackstable("tracks");
    QString searchstring=QString("artist_id= %1 and album_id=%2 and tracknumber=%3").arg(QString::number(artistid),QString::number(albumid),QString::number(tracknumber));
    trackstable.select(searchstring);
    if (trackstable.first())
    {
        QString result=QString::fromUtf8(trackstable.value("trackname").toString());
        trackbox->setCurrentText(result);
    }
}

//Check for given discid, and fill comboboxes given with the result out of database
bool mysqldatabase::checkdiscid(QString discid,QComboBox *artistbox,QComboBox *albumbox)
{
    bool ok;
    QSqlCursor albumstable("albums");
    QString searchstring=QString("cdid=\"%1\"").arg(discid);
    albumstable.select(searchstring);
    if (albumstable.first())
    {
        albumbox->setCurrentText(albumstable.value("albumname").toString());
        long artistid=QString(albumstable.value("artist_id").toString()).toLong(&ok,10);
        QSqlCursor artiststable("artists");
        QString searchstring=QString("artistid=%1").arg(artistid);
        artiststable.select(searchstring);
        if(artiststable.first())
            artistbox->setCurrentText(artiststable.value("artistname").toString());
        return TRUE;
    }
    else
        return FALSE;
}

//Only for the importing of albums with freedb
//+++++++++++++++++++++++++++++++++++++++
//+Insert complete cds into the database+
//+++++++++++++++++++++++++++++++++++++++
void mysqldatabase::writealbum(QString discid,QString discartist,QString discalbum,QString discgenre,long discyear,QStringList *tracklist)
{
    //look if we already have that disc in database
    long albumid=0;
    long artistid=0;
    long genreid=0;
    bool ok;
    //Remove all garbage from the Strings
    discartist=stripunwantedSigns(discartist).utf8();
    discalbum=stripunwantedSigns(discalbum).utf8();
    discgenre=stripunwantedSigns(discgenre).utf8();
    QSqlCursor albumstable("albums");
    QSqlCursor artiststable("artists");
    QSqlCursor genrestable("genres");
    QSqlCursor trackstable("tracks");
    QString searchstring;
    if (!discid.isEmpty())
    {
        searchstring=QString("cdid=%1").arg(discid);
        albumstable.select(searchstring);
        if (albumstable.first())
        {
            //album exists already, so we do not need to insert artist and album,only fetch artistid and albumid
            artistid=QString(albumstable.value("artist_id").toString())
                     .toLong(&ok,10);
            albumid=QString(albumstable.value("albumid").toString()).toLong(&ok,10);
        }
    }
    if (!albumid||!artistid)
    {
        //album does not exist, so check for the artist first and than generate a new album entry
        searchstring=QString("artistname=\"%1\"").arg(discartist);
        artiststable.select(searchstring);
        if (!artiststable.first())
        {
            //artist does not exist,so we create it
            QSqlRecord *buffer=artiststable.primeInsert();
            buffer->setValue("artistname",discartist);
            if (!artiststable.insert())
            {
                QSqlError error=artiststable.lastError();
                cerr<<"artistserror: "<<error.text()<<endl;
            }
            else
            {
                //reposition sql-cursor, so we can read out the new id for the artist
                artiststable.select(searchstring);
                artiststable.first();
            }
        }
        //fetch artistid, no matter if new, or already existing
        artistid=QString(artiststable.value("artistid").toString()).toLong(&ok,10);
        //now check if album already exists, but maybe with a different cdid, or no cdid
        //if we have it without cdid,thow entry away,(this deletes all tracks in the album also) and create new one
        bool generatealbum=TRUE;
        searchstring=QString("artist_id=%1 AND albumname=\"%2\"").arg(QString::number(artistid),discalbum);
        albumstable.select(searchstring);
        if (albumstable.first())
        {
            //Check if this version has a cdid
            QString checkid=albumstable.value("cdid").toString();
            if(checkid.isEmpty())
            {
                albumstable.primeDelete();
                albumstable.del();
                generatealbum=TRUE;
            }
            else
                generatealbum=FALSE;
        }
        //do we have to generate an album?
        if (generatealbum)
        {
            //Insert new Album with the cdid
            QSqlRecord *buffer=albumstable.primeInsert();
            buffer->setValue("artist_id",QString::number(artistid));
            buffer->setValue("albumname",discalbum);
            buffer->setValue("cdid",discid);
            buffer->setValue("releaseyear",QString::number(discyear));
            if (!albumstable.insert())
            {
                QSqlError error=albumstable.lastError();
                cerr<<"albumserror: "<<error.text()<<endl;
            }
            else
            {
                //reposition sql-cursor, so we can read out the new id for the album
                albumstable.select(searchstring);
                albumstable.first();
            }
        }
        albumid=QString(albumstable.value("albumid").toString()).toLong(&ok,10);
    }
    //We have an album now for sure, so lets check for the genre
    searchstring=QString("genrename=\"%1\"").arg(discgenre);
    genrestable.select(searchstring);
    if(!genrestable.first())
    {
        //create a new genre
        QSqlRecord *buffer=genrestable.primeInsert()
                           ;
        buffer->setValue("genrename",discgenre);
        if (!genrestable.insert())
        {
            QSqlError error=genrestable.lastError();
            cerr<<"genreserror: "<<error.text()<<endl;
        }
        else
        {
            //reposition sql-cursor, so we can read out the new id for the genre
            genrestable.select(searchstring);
            genrestable.first();
        }
    }
    genreid=QString(genrestable.value("genreid").toString()).toLong(&ok,10);
    //Now we have everithing we need to create the tracks,if they don't already exist
    QStringList::Iterator index=tracklist->begin();
    int trackcounter=1;
    while(index!=tracklist->end())
    {
        *index=QString::fromUtf8(*index);
        searchstring=QString("artist_id=%1 AND album_id=%2 AND trackname=\"%3\"")
                     .arg(QString::number(artistid),QString::number(albumid),QString(*index));
        trackstable.select(searchstring);
        if (!trackstable.first())
        {
            //track does not exist. Create it
            cerr<<"generate new trackentry   with albumid: "<<albumid<<" artistid: "<<artistid<<endl;
            QSqlRecord *buffer=trackstable.primeInsert();
            buffer->setValue("tracknumber",trackcounter);
            buffer->setValue("trackname",QString(*index));
            buffer->setValue("artist_id",QString::number(artistid));
            buffer->setValue("album_id",QString::number(albumid));
            buffer->setValue("genre_id",QString::number(genreid));
            if (!trackstable.insert())
            {
                QSqlError error=trackstable.lastError();
                cerr<<"trackserror: "<<error.text()<<endl;
            }
        }
        else
        {
            //Track exists already, so we only make a prime-update with it
            cerr<<"update track"<<endl;
            QSqlRecord *buffer=trackstable.primeUpdate();
            buffer->setValue("tracknumber",trackcounter);
            buffer->setValue("genre_id",QString::number(genreid));
            if (!trackstable.update())
            {
                QSqlError error=trackstable.lastError();
                cerr<<"trackserror: "<<error.text()<<endl;
            }
        }
        trackcounter++;
        index++;
    }
}

//new version for saving tags
void mysqldatabase::writetag(mediatag *Song,QString actualfile)
{
    //set all foreign indexes to 0
    long artistindex=0;
    long albumindex=0;
    long genreindex=0;
    long trackindex=0;
    long fileindex=0;
    //Fill up tags if not propper set
    if (Song->album.isEmpty())
        Song->album="no album";
    if (Song->title.isEmpty())
        Song->title="no songname";
    if (Song->artist.isEmpty())
        Song->artist="no artist";
    if (Song->genre.isEmpty())
        Song->genre="no genre";
    artistindex=checkArtist(stripunwantedSigns(Song->artist));
    albumindex=checkAlbum(stripunwantedSigns(Song->album),Song->year,artistindex);
    genreindex=checkGenre(stripunwantedSigns(Song->genre));
    trackindex=checkTrack(stripunwantedSigns(Song->title),Song->number,artistindex,albumindex,genreindex);
    fileindex=checkFile(actualfile,trackindex);
}

void mysqldatabase::updatetag(mediatag *Song,QString actualfile)
{
    QString savefilename;
    //No "-signs are allowed in the database, so we have to remove them,otherwise we dont find a thing
    savefilename=actualfile.remove('"');
    if (savefilename.length()>200)
        savefilename=savefilename.right(200);
    //Look for the right filenumber in the filestable
    QSqlCursor filestable("files");
    QString filesearch=QString("filename =\"%1\"").arg(savefilename);
    filestable.select(filesearch);
    if(!(filestable.first()))
    {
        //file does not exist in db, use writetag-routine instead
        writetag(Song,actualfile);
    }
    else
    {
        //First remove all unwanted signs from the tag
        Song->album=stripunwantedSigns(Song->album);
        Song->artist=stripunwantedSigns(Song->artist);
        Song->genre=stripunwantedSigns(Song->genre);
        //Check if other file points to this trackentry
        //Pull out the trackindex and the fileindex from the files-table, and check all values
        bool ok;
        long artistindex=0;
        long albumindex=0;
        long genreindex=0;
        long trackindex=0;
        long fileindex=0;
        trackindex=QString(filestable.value("track_id").toString()).toLong(&ok,10);
        fileindex=QString(filestable.value("fileid").toString()).toLong(&ok,10);
        QString tracksearch=QString("track_id =\"%1\"").arg(QString::number(trackindex));
        filestable.select();
        filestable.select(tracksearch);
        bool other=FALSE;
        while (filestable.next()&&!other)
        {
            //compare fileindex with the first one
            if (QString(filestable.value("fileid").toString()).toLong(&ok,10)!=fileindex)
                other=TRUE;
        }
        if (!other)
        {
            //We have the only file, that uses this trackid, so we can do what we want
            //fetch new datevalue
            QFileInfo checkfile(actualfile.local8Bit());
            QDateTime lastmod=checkfile.lastModified();
            QString modstring=lastmod.toString(Qt::ISODate);
            //#######################################################################################################################
            //##                                      Updating database in here                                                    ##
            //#######################################################################################################################
            //First get all indexes out of the tracks-table
            QString trackname;
            int tracknumber=0;
            QSqlCursor trackstable("tracks");
            QString tracksearch=QString("trackid =\"%1\"").arg(QString::number(trackindex));
            trackstable.select(tracksearch);
            if(trackstable.first())
            {
                artistindex=QString(trackstable.value("artist_id").toString()).toLong(&ok,10);
                albumindex=QString(trackstable.value("album_id").toString()).toLong(&ok,10);
                genreindex=QString(trackstable.value("genre_id").toString()).toLong(&ok,10);
                trackname=trackstable.value("trackname").toString();
                tracknumber=QString(trackstable.value("tracknumber").toString()).toInt(&ok,10);
            }
            //now get comparestrings out of the tables
            QString artistname=translateartist(artistindex);
            //albumstable
            //A translatefunction for album is here, but we need the year also
            QSqlCursor albumstable("albums");
            QString albumsearch=QString("albumid =\"%1\"").arg(QString::number(albumindex));
            albumstable.select(albumsearch);
            albumstable.first();
            QString albumname=albumstable.value("albumname").toString();
            int year=QString(albumstable.value("releaseyear").toString()).toInt(&ok,10);
            //genrestable
            QString genrename=translategenre(genreindex);
            //now initialize the compare values.
            bool albumchanged=FALSE;
            bool artistchanged=FALSE;
            bool genrechanged=FALSE;
            bool tracknamechanged=FALSE;
            bool tracknumberchanged=FALSE;
            bool yearchanged=FALSE;
            if (albumname.lower().compare(Song->album.lower()))
                albumchanged=TRUE;
            if (artistname.lower().compare(Song->artist.lower()))
                artistchanged=TRUE;
            if (genrename.lower().compare(Song->genre.lower()))
                genrechanged=TRUE;
            if (trackname.lower().compare(Song->title.lower()))
                tracknamechanged=TRUE;
            if (tracknumber!=Song->number)
                tracknumberchanged=TRUE;
            if (year!=Song->year)
                yearchanged=TRUE;
            long newalbumindex=0;
            long newartistindex=0;
            //Everything initialized for updating. Lets start
            //##############################################################################################
            //##                               Album updated                                              ##
            //##############################################################################################
            if (albumchanged)
            {
                //Generate new albumentry, if it is not existing
                newalbumindex=checkAlbum(Song->album,Song->year,artistindex);
                //update fields for that song to match the new albumnumber and delete the empty album
                QString tracksearch=QString("trackid =\"%1\"").arg(QString::number(trackindex));
                trackstable.select(tracksearch);
                if (trackstable.next())
                {
                    QSqlRecord *buffer=trackstable.primeUpdate();
                    buffer->setValue("album_id",QString::number(newalbumindex));
                    trackstable.update();
                    trackstable.select();
                    //Check if any other tracks exist for that album.
                    //if not: Just delete the old album.
                    other=FALSE;
                    QSqlCursor trackstable("tracks");
                    QString tracksearch=QString("album_id =\"%1\"").arg(QString::number(translatealbum(albumname)));
                    trackstable.select(tracksearch);
                    bool other=FALSE;
                    while (trackstable.next()&&!other)
                    {
                        //compare fileindex with the first one
                        if (QString(trackstable.value("trackid").toString()).toLong(&ok,10)!=trackindex)
                            other=TRUE;
                    }
                    if (!other)
                    {

                        QSqlCursor albumstable("albums");
                        QString albumsearch=QString("albumid =\"%1\"").arg(QString::number(albumindex));
                        albumstable.select(albumsearch);
                        if(albumstable.first())
                        {
                            //We have an entry for that filename, so we can delete it
                            albumstable.primeDelete();
                            albumstable.del();
                        }
                    }
                }
            }
            //##############################################################################################
            //##                               Artist updated                                              ##
            //##############################################################################################
            if (artistchanged)
            {
                //Generate new artistentry, if it is not existing
                newartistindex=checkArtist(Song->artist);
                if (newalbumindex&&newalbumindex!=albumindex)
                {
                    //If a new album was generated before, modify that one
                    QSqlCursor albumstable("albums");
                    QString albumsearch =QString("albumid =\"%1\"").arg(QString::number(newalbumindex));
                    albumstable.select(albumsearch);
                    if(albumstable.first())
                    {
                        QSqlRecord *buffer=albumstable.primeUpdate();
                        buffer->setValue("artist_id",QString::number(newalbumindex));
                        albumstable.update();
                    }
                }
                else
                {
                    //Check if artist already has album of that name, and generate it if necessary
                    newalbumindex=checkAlbum(Song->album,Song->year,newartistindex);
                }
                //update fields for that song to match the new artistnumber and delete the empty artist
                QString tracksearch=QString("trackid =\"%1\"").arg(QString::number(trackindex));
                trackstable.select(tracksearch);
                if (trackstable.next())
                {
                    QSqlRecord *buffer=trackstable.primeUpdate();
                    buffer->setValue("artist_id",QString::number(newartistindex));
                    buffer->setValue("album_id",QString::number(newalbumindex));
                    trackstable.update();
                    trackstable.select();
                    //Check if any other tracks exist from that artist.
                    //if not: Just delete the old artist.
                    other=FALSE;
                    QSqlCursor trackstable("tracks");
                    QString tracksearch=QString("artist_id =\"%1\"").arg(QString::number(translateartist(artistname)));
                    trackstable.select(tracksearch);
                    bool other=FALSE;
                    while (trackstable.next()&&!other)
                    {
                        //compare fileindex with the first one
                        if (QString(trackstable.value("trackid").toString()).toLong(&ok,10)!=trackindex)
                            other=TRUE;
                    }
                    if (!other)
                    {
                        QSqlCursor artiststable("artists");
                        QString artistsearch=QString("artistid =\"%1\"").arg(QString::number(artistindex));
                        artiststable.select(artistsearch);
                        if(artiststable.first())
                        {
                            //We have an entry for that filename, so we can delete it
                            artiststable.primeDelete();
                            artiststable.del();
                        }
                    }
                }
            }
            //##############################################################################################
            //##                               Genre updated                                              ##
            //##############################################################################################
            if (genrechanged)
            {
                //Generate new genre-entry, if it is not existing
                long newgenreindex=checkGenre(Song->genre);
                //update fields for that song to match the new genrenumber and delete the empty genre
                QString tracksearch=QString("trackid =\"%1\"").arg(QString::number(trackindex));
                trackstable.select(tracksearch);
                if (trackstable.next())
                {
                    QSqlRecord *buffer=trackstable.primeUpdate();
                    buffer->setValue("genre_id",QString::number(newgenreindex));
                    trackstable.update();
                    trackstable.select();
                    //Check if any other tracks exist with that genre.
                    //if not: Just delete the old genre.
                    other=FALSE;
                    QSqlCursor trackstable("tracks");
                    QString tracksearch=QString("genre_id =\"%1\"").arg(QString::number(translategenre(genrename)));
                    trackstable.select(tracksearch);
                    bool other=FALSE;
                    while (trackstable.next()&&!other)
                    {
                        //compare fileindex with the first one
                        if (QString(trackstable.value("trackid").toString()).toLong(&ok,10)!=trackindex)
                            other=TRUE;
                    }
                    if (!other)
                    {
                        QSqlCursor genrestable("genres");
                        QString genresearch=QString("genreid =\"%1\"").arg(QString::number(genreindex));
                        genrestable.select(genresearch);
                        if(genrestable.first())
                        {
                            //We have an entry for that filename, so we can delete it
                            genrestable.primeDelete();
                            genrestable.del();
                        }
                    }
                }
            }
            //##############################################################################################
            //##                           Trackname or Tracknumber updated				##
            //##                 No foreign indexes in this cases, so updating is easier                  ##
            //##############################################################################################
            if (tracknumberchanged||tracknamechanged)
            {
                //Update everything at once, to don't make a 2-times update, if all two things change
                //update fields for that song to match the new genrenumber and delete the empty genre
                QString tracksearch=QString("trackid =\"%1\"").arg(QString::number(trackindex));
                trackstable.select(tracksearch);
                if (trackstable.next())
                {
                    QSqlRecord *buffer=trackstable.primeUpdate();
                    buffer->setValue("tracknumber",QString::number(Song->number));
                    buffer->setValue("trackname",Song->title);
                    trackstable.update();
                    trackstable.select();
                }
            }
            //##############################################################################################
            //##                                    Year updated						##
            //##                 No foreign indexes in this cases, so updating is easier                  ##
            //##############################################################################################
            if (yearchanged)
            {
                //First of all, set album to newalbum, if we generated an album before
                if(newalbumindex)
                    albumindex=newalbumindex;
                QString albumsearch=QString("albumid =\"%1\"").arg(QString::number(albumindex));
                trackstable.select(tracksearch);
                if (trackstable.next())
                {
                    QSqlRecord *buffer=trackstable.primeUpdate();
                    buffer->setValue("tracknumber",QString::number(Song->number));
                    buffer->setValue("trackname",Song->title);
                    trackstable.update();
                    trackstable.select();
                }
            }
            //########################################################################################################################
            //Last but not least: Update the modified-stamp for this file
            QSqlCursor filestable("files");
            QString filesearch=QString("fileid =\"%1\"").arg(QString::number(fileindex));
            filestable.select(filesearch);
            if(filestable.first())
            {
                QSqlRecord *buffer=filestable.primeUpdate();
                buffer->setValue("modified",modstring);
                filestable.update();
            }
        }
        else
        {
            //This Trackid is also used by an other file, so we have to make a new trackindex
            writetag(Song,actualfile);
        }
    }
}


//A bunch of standard search and create-tools, to make mysql-class a bit more highlevel, and easier to understand.

//Remove file out of database
//Leave all other tables untouched
void mysqldatabase::removefile(QString filetoremove)
{
    filetoremove=filetoremove.remove('"');
    if (filetoremove.length()>200)
        filetoremove=filetoremove.right(200);
    QSqlCursor filestable("files");
    QString filesearch=QString("filename =\"%1\"").arg(filetoremove);
    filestable.select(filesearch);
    if(filestable.first())
    {
        //We have an entry for that filename, so we can delete it
        filestable.primeDelete();
        filestable.del();
    }
}

//Check, if the file was modified, since the last entry into the database
bool mysqldatabase::checkModified(QString filetocheck)
{
    bool filealreadychecked=0;
    QString savefilename;
    //No "-signs are allowed in the database, so we have to remove them,otherwise we dont find a thing
    savefilename=filetocheck.remove('"');
    if (savefilename.length()>200)
        savefilename=savefilename.right(200);
    //first check for the last modification date, and generate our string for the table
    QFileInfo checkfile(filetocheck.local8Bit());
    QDateTime lastmod=checkfile.lastModified();
    QString modstring=lastmod.toString(Qt::ISODate);
    //we have the modification-string, lets compare it with value in database if it already exists.
    QSqlCursor filestable("files");
    QString filesearch=QString("filename =\"%1\"").arg(savefilename);
    filestable.select(filesearch);
    if(!(filestable.first()))
        filealreadychecked=FALSE;
    else
    {
        //compare the date with the one in database
        QString datefromdatabase=QString(filestable.value("modified").toString());
        if (!datefromdatabase.compare(modstring))
            filealreadychecked=TRUE;
        else
            filealreadychecked=FALSE;
    }
    return filealreadychecked;
}

//Remove all unwanted signes from given String
QString mysqldatabase::stripunwantedSigns(QString giventext)
{
    giventext=giventext.remove('"');
    while (giventext.startsWith(" "))
        giventext=giventext.right(giventext.length()-1);
    while (giventext.endsWith(" "))
        giventext=giventext.left(giventext.length()-1);
    return giventext;
}

/*give a String to search for in the artisttable.
 *Creates a new artist,if it is not existing and gives back its index in the table*/
long mysqldatabase::checkArtist(QString artistname)
{
    long artistindex=0;
    artistname=artistname.utf8();
    QSqlCursor artiststable("artists");
    QString artistsearch=QString("artistname =\"%1\"").arg(artistname);
    artiststable.select(artistsearch);
    if(!(artiststable.first()))//If artist doesn't exist, create a db-entry
    {
        QSqlRecord *buffer=artiststable.primeInsert();
        buffer->setValue("artistname",artistname);
        if (!artiststable.insert())
        {
            QSqlError error=artiststable.lastError();
            cerr<<"artisterror:"<<error.text()<<endl;
        }

        //reposition sql-cursor, so we can read out the new id for the artist
        artiststable.select(artistsearch);
        artiststable.first();
    }
    bool ok;
    artistindex=(QString(artiststable.value("artistid").toString())).toLong(&ok,10);
    return artistindex;
}

/*give a album-String, a year-string and a artsitindex to function to search for in albumstable
 *if that album does not exist, create it. Give back the albumindex*/
long mysqldatabase::checkAlbum(QString albumname,int year,long artistindex)
{
    long albumindex=0;
    albumname=albumname.utf8();
    QSqlCursor albumstable("albums");
    QString albumsearch=QString("albumname =\"%1\" and artist_id=\"%2\"").arg(albumname,QString::number(artistindex));
    albumstable.select(albumsearch);
    if(!(albumstable.first()))//If album doesn't exist, create a db-entry
    {
        QSqlRecord *buffer=albumstable.primeInsert();
        buffer->setValue("albumname",albumname);
        buffer->setValue("artist_id",QString::number(artistindex));
        buffer->setValue("releaseyear",year);
        if (!albumstable.insert())
        {
            QSqlError error=albumstable.lastError();
            cerr<<"albumserror:"<<error.text()<<endl;
        }
        //reposition sql-cursor, so we can read out the new id for the album
        albumstable.select(albumsearch);
        albumstable.first();
    }
    bool ok;
    albumindex=(QString(albumstable.value("albumid").toString())).toLong(&ok,10);
    return albumindex;
}

/*give a String to search for in the genrestable.
 *Creates a new genre,if it is not existing and gives back its index in the table*/
long mysqldatabase::checkGenre(QString genrename)
{
    long genreindex=0;
    genrename=genrename.utf8();
    QSqlCursor genrestable("genres");
    QString genresearch=QString("genrename =\"%1\"").arg(genrename);
    genrestable.select(genresearch);
    if(!(genrestable.first()))//If genre doesn't exist, create a db-entry
    {
        QSqlRecord *buffer=genrestable.primeInsert();
        buffer->setValue("genrename",genrename);
        if (!genrestable.insert())
        {
            QSqlError error=genrestable.lastError();
            cerr<<"genreserror: "<<error.text()<<endl;
        }
        //reposition sql-cursor, so we can read out the new id for the album
        genrestable.select(genresearch);
        genrestable.first();
    }
    bool ok;
    genreindex=(QString(genrestable.value("genreid").toString())).toLong(&ok,10);
    return genreindex;
}

/*give a trackname, tracknumber, and all indexes from the other tables for the search in trackstable
 *Create a new track, if it is not existing, and give back the index in the table*/
long mysqldatabase::checkTrack(QString trackname,int tracknumber,long artistindex,long albumindex,long genreindex)
{
    long trackindex=0;
    trackname=trackname.utf8();
    QSqlCursor trackstable("tracks");
    QString tracksearch=QString("trackname=\"%1\" and album_id=\"%2\" and artist_id=\"%3\"").arg(trackname,QString::number(albumindex),QString::number(artistindex));
    trackstable.select(tracksearch);
    if(!(trackstable.first()))//If Song doesn't exist, create a db-entry
    {
        QSqlRecord *buffer=trackstable.primeInsert();
        buffer->setValue("album_id",QString::number(albumindex));
        buffer->setValue("artist_id",QString::number(artistindex));
        buffer->setValue("genre_id",QString::number(genreindex));
        buffer->setValue("trackname",trackname);
        buffer->setValue("tracknumber",tracknumber);
        if(!trackstable.insert())
        {
            QSqlError error=trackstable.lastError();
            cerr<<"trackserror"<<error.text()<<endl;
        }
        //reposition sql-cursor, so we can read out the new id for the track
        trackstable.select(tracksearch);
        trackstable.first();
    }
    bool ok;
    trackindex=(QString(trackstable.value("trackid").toString())).toLong(&ok,10);
    return trackindex;
}

/*Give a filename to search for in files-table
 *If it does not exist already, create it with the given trackindex, and an actual tiestamp
 *Return the fileindex from the table*/
long mysqldatabase::checkFile(QString filename,long trackindex)
{
    long fileindex=0;
    //Write the tracknumber, a datestamp and the filename in table for files
    //limit the filename to 200 signs (from right)
    QString savefilename;
    //No "-signs are allowed in the database, so we have to remove them,otherwise we dont find a thing
    savefilename=filename.remove('"').local8Bit();
    if (savefilename.length()>200)
        savefilename=savefilename.right(200);
    //first check for the last modification date, and generate our string for the table
    QFileInfo checkfile(filename.local8Bit());
    QDateTime lastmod=checkfile.lastModified();
    QString modstring=lastmod.toString(Qt::ISODate);
    //we have the modification-string, lets generate the entry if it doesnt already exist.
    QSqlCursor filestable("files");
    QString filesearch=QString("filename =\"%1\"").arg(savefilename);
    filestable.select(filesearch);
    if(!(filestable.first()))//If file does not exist, create a db-entry
    {
        QSqlRecord *buffer=filestable.primeInsert();
        buffer->setValue("filename",savefilename.utf8());
        buffer->setValue("track_id",QString::number(trackindex));
        buffer->setValue("modified",modstring);
        if(!filestable.insert())
        {
            QSqlError error=filestable.lastError();
            cerr<<"fileserror"<<error.text()<<" for file "<<filename<<endl;
        }
    }
    else
    {
        //We already have that file, so we update it with the new tags, and datestamp
        QSqlRecord *buffer=filestable.primeUpdate();
        buffer->setValue("track_id",QString::number(trackindex));
        buffer->setValue("modified",modstring);
        filestable.update();
    }
    bool ok;
    fileindex=(QString(filestable.value("fileid").toString())).toLong(&ok,10);
    return fileindex;
}

//All create table functions
//It's easier to maintain this way, and they are usable from other functions than createdb
void mysqldatabase::generateAlbumtable()
{
    QSqlQuery querystatement;
    querystatement.exec ("CREATE TABLE albums ("
                         "albumid BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,"
                         "albumname VARCHAR (80),"
                         "artist_id BIGINT UNSIGNED,"
                         "cdid VARCHAR (10),"
                         "releaseyear INT UNSIGNED,"
                         "PRIMARY KEY (albumid),"
                         "INDEX art_id(artist_id),"
                         "FOREIGN KEY (artist_id) REFERENCES artists (artistid) ON DELETE CASCADE"
                         ") TYPE=INNODB CHARACTER SET=utf8;");
}

void mysqldatabase::generateArtisttable()
{
    QSqlQuery querystatement;
    querystatement.exec ("CREATE TABLE artists ("
                         "artistid BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,"
                         "artistname VARCHAR (80),"
                         "artistcountry VARCHAR (50),"
                         "PRIMARY KEY (artistid)"
                         ") TYPE=INNODB CHARACTER SET=utf8;");
}

void mysqldatabase::generateGenretable()
{
    QSqlQuery querystatement;
    querystatement.exec ("CREATE TABLE genres ("
                         "genreid BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,"
                         "genrename VARCHAR (80),"
                         "PRIMARY KEY (genreid)"
                         ") TYPE=INNODB CHARACTER SET=utf8;");
}

void mysqldatabase::generateTracktable()
{
    QSqlQuery querystatement;
    querystatement.exec ("CREATE TABLE tracks ("
                         "trackid BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,"
                         "tracknumber INT,"
                         "trackname VARCHAR (80),"
                         "artist_id BIGINT UNSIGNED,"
                         "album_id BIGINT UNSIGNED,"
                         "genre_id BIGINT UNSIGNED,"
                         "PRIMARY KEY (trackid),"
                         "INDEX art_id(artist_id),"
                         "INDEX alb_id(album_id),"
                         "INDEX gen_id(genre_id),"
                         "FOREIGN KEY (artist_id) REFERENCES artists (artistid) ON DELETE CASCADE,"
                         "FOREIGN KEY (album_id) REFERENCES albums (albumid) ON DELETE CASCADE,"
                         "FOREIGN KEY (genre_id) REFERENCES genres (genreid) ON DELETE CASCADE"
                         ") TYPE=INNODB CHARACTER SET=utf8;");

}

void mysqldatabase::generateFiletable()
{
    QSqlQuery querystatement;
    querystatement.exec ("CREATE TABLE files ("
                         "fileid BIGINT NOT NULL AUTO_INCREMENT,"
                         "filename VARCHAR(200),"
                         "modified VARCHAR(20),"
                         "track_id BIGINT UNSIGNED,"
                         "INDEX tr_id(track_id),"
                         "PRIMARY KEY (fileid),"
                         "FOREIGN KEY (track_id) REFERENCES tracks (trackid) ON DELETE CASCADE"
                         ") TYPE=INNODB CHARACTER SET=utf8;");
}
