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

filtergenerator::filtergenerator(QString givenfile)
{
    ready=FALSE;
    this->setModal(TRUE);
    this->setCaption(i18n("Create new filter"));
    matchfile=givenfile;
    filter=givenfile;
    alreadyselected=new int[matchfile.length()+1];
    for (uint i=0;i<=matchfile.length();i++)
        alreadyselected[i]=0;
    mainlayout=new QVBoxLayout(this);
    filterline=new QLabel(QString(i18n("<center>actual filter<br><b>%1</b></center>")).arg(matchfile),this);
    mainlayout->addWidget(filterline);
    filtersbox=new QGroupBox(2,Qt::Vertical,this);
    mainlayout->addWidget(filtersbox);
    //the text is only selectable, to build up new filter, out of marked text
    fileline=new QLineEdit(filtersbox);
    fileline->setText(matchfile);
    fileline->setReadOnly(TRUE);
    //All filterbutton get in here
    filterbuttonsbox=new QGroupBox(4,Qt::Horizontal,filtersbox);
    yearbutton=new QPushButton("#YEAR#",filterbuttonsbox);
    artistbutton=new QPushButton("#BAND#",filterbuttonsbox);
    songbutton=new QPushButton("#TITLE#",filterbuttonsbox);
    trackbutton=new QPushButton("#TRACK#",filterbuttonsbox);
    albumbutton=new QPushButton("#ALBUM#",filterbuttonsbox);
    genrebutton=new QPushButton("#GENRE#",filterbuttonsbox);
    formatbutton=new QPushButton("#FORMAT#",filterbuttonsbox);
    mainlayout->addWidget(filterbuttonsbox);
    //for ok and Cancelbuttons
    userbuttons=new QGroupBox(3,Qt::Horizontal,this);
    okbutton=new QPushButton(i18n("Ok"),userbuttons);
    restorebutton=new QPushButton(i18n("Restore"),userbuttons);
    Cancelbutton=new QPushButton(i18n("Cancel"),userbuttons);
    mainlayout->addWidget(userbuttons);
    KIconLoader *loader=new KIconLoader("KYamo");
    QString picname;
    picname="ok.png";
    okpic=loader->loadIcon(picname,KIcon::NoGroup);
    QIconSet buttonset(okpic);
    okbutton->setIconSet(buttonset);
    picname="cancel.png";
    Cancelpic=loader->loadIcon(picname,KIcon::NoGroup);
    buttonset=QIconSet(Cancelpic);
    Cancelbutton->setIconSet(buttonset);
    picname="reload.png";
    restorepic=loader->loadIcon(picname,KIcon::NoGroup);
    buttonset=QIconSet(restorepic);
    restorebutton->setIconSet(buttonset);
    this->show();
    delete loader;
    connect (yearbutton,SIGNAL(clicked()),SLOT(yearslot()));
    connect (artistbutton,SIGNAL(clicked()),SLOT(artistslot()));
    connect (songbutton,SIGNAL(clicked()),SLOT(songslot()));
    connect (trackbutton,SIGNAL(clicked()),SLOT(trackslot()));
    connect (albumbutton,SIGNAL(clicked()),SLOT(albumslot()));
    connect (genrebutton,SIGNAL(clicked()),SLOT(genreslot()));
    connect (formatbutton,SIGNAL(clicked()),SLOT(formatslot()));
    connect (restorebutton,SIGNAL(clicked()),SLOT(restoreslot()));
    connect (okbutton,SIGNAL(clicked()),SLOT(okslot()));
    connect (Cancelbutton,SIGNAL(clicked()),SLOT(Cancelslot()));
}

filtergenerator::~ filtergenerator()
{
    delete alreadyselected;
    delete filterline;
    delete fileline;
    delete okbutton;
    delete restorebutton;
    delete Cancelbutton;
    delete formatbutton;
    delete yearbutton;
    delete artistbutton;
    delete songbutton;
    delete trackbutton;
    delete albumbutton;
    delete genrebutton;
    delete filterbuttonsbox;
    delete filtersbox;
    delete userbuttons;
    delete mainlayout;
}

void filtergenerator::albumslot()
{
    if (setselected(5))
        redrawfilter();
}

void filtergenerator::artistslot()
{
    if (setselected(2))
        redrawfilter();
}


void filtergenerator::formatslot()
{
    if (setselected(7))
        redrawfilter();
}


void filtergenerator::genreslot()
{
    if (setselected(6))
        redrawfilter();
}


void filtergenerator::songslot()
{
    if (setselected(3))
        redrawfilter();
}


void filtergenerator::trackslot()
{
    if (setselected(4))
        redrawfilter();
}


void filtergenerator::yearslot()
{
    if (setselected(1))
        redrawfilter();
}

void filtergenerator::redrawfilter()
{
    //Go through the alreadyselected-field and replace all signs that are already selected with apropriate filter
    filter=QString::null;
    int memnomic=0;
    for (uint i=0;i<=matchfile.length()-1;i++)
    {
        if ((memnomic=alreadyselected[i]))
        {
            //This part is already occupied, so we read the field through till the end of this memnomic
            while(alreadyselected[i]==memnomic)
                i++;
            i--;//go one sign back, to get the next sign, after this memnomic
            switch (memnomic)
            {
            case 1:
                filter.append("#YEAR#");
                break;
            case 2:
                filter.append("#BAND#");
                break;
            case 3:
                filter.append("#SONG#");
                break;
            case 4:
                filter.append("#TRACK#");
                break;
            case 5:
                filter.append("#ALBUM#");
                break;
            case 6:
                filter.append("#GENRE#");
                break;
            case 7:
                filter.append("#FORMAT#");
                break;
            }
        }
        else
            filter.append(matchfile.at(i));
    }
    filterline->setText(QString(i18n("<center>actual filter<br><b>%1</b></center>")).arg(filter));
}

bool filtergenerator::setselected(int mnemnomicvalue)
{
    bool selecetionabort=FALSE;
    QString textbuffer=fileline->selectedText();
    if (!textbuffer.isEmpty())
    {
        //Don't allow selection of all the text
        uint startposition=fileline->selectionStart();
        if (!(textbuffer.length()==matchfile.length()))
        {
            //Check if the selected text is still available, and replace it in filterline if it is
            //First get the startindex of the selection
            for (uint i=startposition;(i<=startposition+textbuffer.length()-1)&&!selecetionabort;i++)
            {
                if (alreadyselected[i])
                {
                    selecetionabort=TRUE;
                    errordisplay=i18n("You already have selected one of this signs!");
                }
            }
            //check if we already have that memnomic selected
            for (uint i=0;(i<=matchfile.length())&&!selecetionabort;i++)
            {
                if (alreadyselected[i]==mnemnomicvalue)
                {
                    selecetionabort=TRUE;
                    errordisplay=i18n("You already have selected this memnomic!");
                }
            }
            //Check if we have some spare room between the mnemnomics
            if (startposition)
            {
                //Check if the sign on the left side, and on the right side are still free
                if (!(alreadyselected[startposition-1]==0))
                {
                    selecetionabort=TRUE;
                    errordisplay=i18n("You have to leave some signs on the borders of the mnemnomics, so the filter can work!");
                }
                if (!(alreadyselected[startposition+textbuffer.length()]==0))
                {
                    selecetionabort=TRUE;
                    errordisplay=i18n("You have to leave some signs on the borders of the mnemnomics, so the filter can work!");
                }
            }
            else
            {
                //only check the right side, cause we are on the start of the text
                if (!(alreadyselected[textbuffer.length()]==0))
                {
                    selecetionabort=TRUE;
                    errordisplay=i18n("You have to leave some signs on the borders of the mnemnomics, so the filter can work!");
                }
            }
            if (!selecetionabort)
            {
                //We can have that part of the line, so we set it occupied, and show the user the resulting filter
                for (uint i=startposition;(i<=startposition+textbuffer.length()-1)&&!selecetionabort;i++)
                    alreadyselected[i]=mnemnomicvalue;//set as memnomic
                redrawfilter();
            }
        }
        else
        {
            errordisplay=i18n("It is no filter, if you select all the text!");
            selecetionabort=TRUE;
        }
        if (selecetionabort)
        {
            //tell the user, why nothing happens
            QMessageBox::information(0,i18n("Selection wrong"),errordisplay,i18n("Ok"));
        }
    }
    else
    {
        QMessageBox::information(0,i18n("Selection wrong"),i18n("You have to select some text for that memnomic"),i18n("Ok"));
    }
    return !selecetionabort;
}

void filtergenerator::restoreslot()
{
    //Restore the start-state
    for (uint i=0;i<=matchfile.length()-1;i++)
        alreadyselected[i]=0;
    filterline->setText(QString(i18n("<center>actual filter<br><b>%1</b></center>")).arg(matchfile));
    filter=matchfile;
}

void filtergenerator::okslot()
{
    //Check, if we have something that could work in our filter, and generate a new filter if we have
    if((matchfile.compare(filter))!=0)
    {
        //We have a filter, calling function can catch it from this function
        ready=TRUE;
    }
    else
        QMessageBox::information(0,i18n("Filter wrong"),i18n("You did not create a filter!"),i18n("Ok"));
}

void filtergenerator::Cancelslot()
{
    ready=-1;
}

void filtergenerator::closeEvent(QCloseEvent *ce)
{
    //We prefer this way to close the widget, so we catch the closeevent
    ready=-1;
    ce->accept();
}
