/***************************************************************************
 *   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 "filter.h"

extern rcdatei einstellungen;

filter::filter(QString text,QString path)
{
    /*process filtertext, and set filterOk to 0, if filter wont work
    write problem into errorText, so user can get info about the reason filter does not work*/
    destdir=path;
    mnemnomiccounter=0;
    filtertext=text;
    filterparts=new QStringList();
    if (filtertext.endsWith("/")||filtertext.startsWith("/"))
    {
        errorText=QString(i18n("You need at least one sign for diretoryname<br>Filter does not work!"));
        filterOk=FALSE;
        return;
    }
    /*Split filtertext into parts, and put it in a stringlist
      all mnemnomics start and end with #, at least one memnomic is needed*/
    int position=0;
    while ((position=filtertext.find('#'))!=-1)
    {
        if (position)//everything in front of # is a normal filterstring, if no / is in
        {
            QString parttext=filtertext.left(position);
            filtertext.remove(0,position);
            if (!parttext.contains('/'))
            {
                filterparts->append(parttext);
            }
            else
            {
                //remove every / and move it into filterparts as a directoryslash
                while((position=parttext.find('/'))!=-1)
                {
                    if (position)//if / is not first sign
                    {
                        filterparts->append(parttext.left(position));
                        parttext.remove(0,position+1);
                        filterparts->append("/");
                    }
                    else
                    {
                        //check if last entry of filterparts is also /
                        if (filterparts->last().compare("/"))
                        {
                            filterparts->append("/");
                            parttext.remove(0,1);
                        }
                        else
                        {
                            errorText=QString(i18n("You need at least one sign for diretoryname<br>Filter does not work!"));
                            filterOk=FALSE;
                            return;
                        }
                    }
                    if (!parttext.isEmpty()&&!parttext.contains('/'))
                    {
                        filterparts->append(parttext);
                    }
                }
            }
        }
        else //search for next #
        {
            filtertext=filtertext.remove(0,position+1);
            position=filtertext.find('#');
            QString memnomic=filtertext.left(position);
            //check if memnomic is valid
            memnomic=QString("#%1#").arg(memnomic);
            if (checkMemnomic(memnomic))
            {
                filterparts->append(memnomic);
                mnemnomiccounter++;
                filtertext.remove(0,position+1);
            }
            else
            {
                filterparts->append(memnomic);
                filtertext.remove(0,position+1);
                errorText=QString(i18n("#-Sign is reserved for mnemnomics<br>Filter does not work!"));
                filterOk=FALSE;
                return;

            }
        }
    }
    //Process the Rest of the filtertext
    if (!filtertext.contains('/'))
    {
        filterparts->append(filtertext);
    }
    else
    {
        //remove every / and move it into filterparts as a directoryslash
        while((position=filtertext.find('/'))!=-1)
        {
            if (position)//if / is not first sign
            {
                //check if last entry of filterparts is also /
                filterparts->append(filtertext.left(position));
                filtertext.remove(0,position+1);
                filterparts->append("/");
            }
            else
            {
                //check if last entry of filterparts is also /
                if (filterparts->last().compare("/"))
                {
                    filterparts->append("/");
                    filtertext.remove(0,position+1);
                }
                else
                {
                    errorText=QString(i18n("You need at least one sign for diretoryname<br>Filter does not work!"));
                    filterOk=FALSE;
                    return;
                }
            }
            if (!filtertext.isEmpty()&&!filtertext.contains('/'))
            {
                filterparts->append(filtertext);
            }
        }
    }
    if (mnemnomiccounter)
        filterOk=TRUE;
    else
    {
        errorText=QString(i18n("You need at least one changeable part in filename.<br>Filter does not work!"));
        filterOk=FALSE;
    }
}

filter::~filter()
{
    delete filterparts;
}

int filter::makeDirectories(QString sourcefile,QString destdir)
{
    /*check if filterdirectories are existing, and generate them if needed
    return -1 if generating directories is not possible and 0 is some tag is missing*/
    mediafile fileinwork(sourcefile);
    if (fileinwork.readsuccess)
    {
        fileinwork.readTags();
        if(fileinwork.containsTag)
        {
            mediatag Song;
            Song=fileinwork.taginfo;
            //First remove all spaces from the beginning and end, and remove other unwanted signs
            stripunwantedsigns(&Song);
            QDir *directory=new QDir(destdir);
            QStringList::Iterator index=filterparts->begin();
            QString currentstring;
            QString buffer;
            while (index!=filterparts->end())
            {
                switch (checkMemnomic( *index))
                {
                case 1:
                    {
                        currentstring=QString("%1%2").arg(currentstring,QString::number(Song.year));
                        break;
                    }
                case 2:
                    {
                        buffer=Song.artist;
                        buffer.replace('/','_');
                        buffer.replace('?',"_");
                        currentstring=QString("%1%2").arg(currentstring,buffer);
                        if (buffer.isEmpty())
                            return 0;
                        break;
                    }
                case 3:
                    {
                        buffer=Song.title;
                        buffer.replace('/','_');
                        buffer.replace('?',"_");
                        currentstring=QString("%1%2").arg(currentstring,buffer);
                        if (buffer.isEmpty())
                            return 0;
                        break;
                    }
                case 4:
                    {
                        if (Song.number<10)
                            currentstring=QString("%10%2").arg(currentstring,QString::number(Song.number));
                        else
                            currentstring=QString("%1%2").arg(currentstring,QString::number(Song.number));
                        break;
                    }
                case 5:
                    {
                        buffer=Song.album;
                        buffer.replace('/','_');
                        buffer.replace('?',"_");
                        currentstring=QString("%1%2").arg(currentstring,buffer);
                        if (buffer.isEmpty())
                            return 0;
                        break;
                    }
                case 6:
                    {
                        buffer=Song.genre;
                        buffer.replace('/','_');
                        buffer.replace('?',"_");
                        currentstring=QString("%1%2").arg(currentstring,buffer);
                        if (buffer.isEmpty())
                            return 0;
                        break;
                    }
                case 0:
                    {
                        if (!QString(*index).compare("/"))
                        {
                            //make directory out of last filteritems,if it doesnt exist already
                            QFileInfo checkdir(QString("%1/%2").arg(directory->path(),currentstring));
                            if (!checkdir.exists())
                            {
                                if (!directory->mkdir(currentstring))
                                {
                                    errorText=QString(i18n("Could not create directory \"%1\" in \"%2\" !")).arg(currentstring,directory->path());
                                    return -1;
                                }
                            }
                            directory->setPath(QString("%1/%2").arg(directory->path(),currentstring));
                            currentstring="";
                        }
                        else
                        {
                            //add current string to last filteritems
                            currentstring=QString("%1%2").arg(currentstring,*index);
                        }
                        break;
                    }
                }
                index++;
            }
            delete directory;
            return 1;
        }
        else
        {
            errorText=QString(i18n("File %1 has no tags!")).arg(sourcefile);
            return -1;
        }
    }
    else
    {
        errorText=QString(i18n("File %1 does not exist anymore!")).arg(sourcefile);
        return -1;
    }
}

int filter::generateName(QString sourcefile)
{
    /*check if filterdirectories are existing, and generate them if needed
    return FALSE if generating directories is not possible*/
    mediafile fileinwork(sourcefile);
    if (fileinwork.readsuccess)
    {
        fileinwork.readTags();
        if(fileinwork.containsTag)
        {
            mediatag Song;
            Song=fileinwork.taginfo;
            stripunwantedsigns(&Song);
            QStringList::Iterator index=filterparts->begin();
            QString currentstring;
            QString buffer;
            while (index!=filterparts->end())
            {
                switch (checkMemnomic( *index))
                {
                case 1:
                    {
                        currentstring=QString("%1%2").arg(currentstring,QString::number(Song.year));
                        break;
                    }
                case 2:
                    {
                        buffer=Song.artist;
                        buffer.replace('/','_');
                        buffer.replace('?',"_");
                        currentstring=QString("%1%2").arg(currentstring,buffer);
                        if (buffer.isEmpty())
                            return 0;
                        break;
                    }
                case 3:
                    {
                        buffer=Song.title;
                        buffer.replace('/','_');
                        buffer.replace('?',"_");
                        currentstring=QString("%1%2").arg(currentstring,buffer);
                        if (buffer.isEmpty())
                            return 0;
                        break;
                    }
                case 4:
                    {
                        if (Song.number<10)
                            currentstring=QString("%10%2").arg(currentstring,QString::number(Song.number));
                        else
                            currentstring=QString("%1%2").arg(currentstring,QString::number(Song.number));
                        break;
                    }
                case 5:
                    {
                        buffer=Song.album;
                        buffer.replace('/','_');
                        buffer.replace('?',"_");
                        currentstring=QString("%1%2").arg(currentstring,buffer);
                        if (buffer.isEmpty())
                            return 0;
                        break;
                    }
                case 6:
                    {
                        buffer=Song.genre;
                        buffer.replace('/','_');
                        buffer.replace('?',"_");
                        currentstring=QString("%1%2").arg(currentstring,buffer);
                        if (buffer.isEmpty())
                            return 0;
                        break;
                    }
                case 0:
                    {
                        currentstring=QString("%1%2").arg(currentstring,*index);
                        break;
                    }
                }
                index++;
            }
            filenamesuggest=currentstring;
            return 1;
        }
        else
        {
            errorText=QString(i18n("File %1 has no tags!")).arg(sourcefile);
            return -1;
        }
    }
    else
    {
        errorText=QString(i18n("File %1 does not exist anymore!")).arg(sourcefile);
        return -1;
    }
}

void filter::stripunwantedsigns(mediatag *workingsong)
{
    //Since we don't want trailing or leading spaces we remove them of every tagstring
    while(workingsong->artist.startsWith(" "))
        workingsong->artist=workingsong->artist.remove(0,1);
    while(workingsong->album.startsWith(" "))
        workingsong->album=workingsong->album.remove(0,1);
    while(workingsong->genre.startsWith(" "))
        workingsong->album=workingsong->album.remove(0,1);
    while(workingsong->title.startsWith(" "))
        workingsong->album=workingsong->album.remove(0,1);
    //Replace all problematic signs with an underscore
    workingsong->artist=workingsong->artist.replace("?","_");
    workingsong->album=workingsong->album.replace("?","_");
    workingsong->genre=workingsong->genre.replace("?","_");
    workingsong->title=workingsong->title.replace("?","_");
}
