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

coverfinder2::coverfinder2(QString searchstring)
{
    //Initialize coverfinderwindow
    this->setCaption("K-Yamo coverfinder");
    selectedcover=0;
    coverindex=0;
    coverstring=searchstring;
    radiogroup=new QButtonGroup(this);
    radiogroup->setExclusive(TRUE);
    this->setModal(TRUE);
    coverfinderlayout=new QVBox(this);
    coverselectorlayout=new QGroupBox(3,Qt::Horizontal,coverfinderlayout);
    buttonbox=new QGroupBox(2,Qt::Horizontal,coverfinderlayout);
    cancelbutton=new QPushButton(i18n("Cancel"),buttonbox);
    KIconLoader *loader=new KIconLoader("KYamo");
    QString picname;
    picname="cancel.png";
    QImage cancelpic;
    cancelpic=loader->loadIcon(picname,KIcon::NoGroup);
    QIconSet buttonset(cancelpic);
    cancelbutton->setIconSet(buttonset);
    okbutton=new QPushButton(i18n("Ok"),buttonbox);
    //deactivate ok, cause we don't have a selected picture yet
    okbutton->setEnabled(FALSE);
    picname="ok.png";
    QImage okpic;
    okpic=loader->loadIcon(picname,KIcon::NoGroup);
    buttonset=QIconSet(okpic);
    okbutton->setIconSet(buttonset);
    delete loader;
    //Make all connections, so the dialog can operate, while we are waiting for covers
    connect (cancelbutton,SIGNAL(clicked()),SLOT(cancelslot()));
    connect (radiogroup,SIGNAL(clicked(int)),SLOT(checkokslot(int)));
    connect (okbutton,SIGNAL(clicked()),SLOT(okslot()));
    //Ask google for the pictures, and than wait till the result from google is ready
    getpicturelinks();
    connect (this,SIGNAL(googlequeryready()),SLOT(fetchcoverlist()));
    connect (this,SIGNAL(newpicturereceived(QImage)),SLOT(addpicturetolayout(QImage)));
    coverfinderlayout->adjustSize();
    coverselectorlayout->adjustSize();
    this->adjustSize();

}

coverfinder2::~ coverfinder2()
{
    cerr<<"coverfinder destrucor"<<endl;
    coverlist.clear();
    linklist.clear();
    delete okbutton;
    delete cancelbutton;
    delete buttonbox;
    delete coverselectorlayout;
    delete coverfinderlayout;
}

void coverfinder2::closeEvent(QCloseEvent*)
{
    //set abortflag
    emit abort();
}

void coverfinder2::getpicturelinks()
{
    coverlist.clear();
    coverlist.setAutoDelete(TRUE);
    linklist.clear();
    linklist.setAutoDelete(TRUE);
    //first of all we a need a url to look for in internet.
    url=new QHttp();
    url->setHost("images.google.com",80);
    QString googlequery=QString("/images?q=%1&ie=ISO-8859-1&hl=en&btnG=Search+Images").arg(coverstring);
    //Start the search over google, than simply wait till the result is there.
    transactionid=url->get
                  (googlequery);
    connect(url,SIGNAL(requestFinished(int, bool)),SLOT(getpicturelist(int,bool)));
}

void coverfinder2::getpicturelist(int trid,bool)
{
    //sort out the result from google;
    if (trid==transactionid)
    {
        QByteArray receiveddata=url->readAll();
        QString buffer;
        for ( uint i = 0;i < receiveddata.count(); i++ )
        {
            char character=receiveddata[(int)i];
            buffer.append(character);
            if (character=='\n')
            {
                while(buffer.lower().contains("dyn.img(\""))
                {
                    //do we still have some urls of images there?
                    int position=(buffer.lower().find("dyn.img(\""));
                    buffer=buffer.right(buffer.length()-(position+9));
                    //ok, find the pic after the third ,                    
                    for (int i=0;i<3;i++)
                    {
                    position=(buffer.lower().find(",\""));
                    buffer=buffer.right(buffer.length()-(position+2));
                    }
                    QString imageurl=buffer.left(buffer.find("\""));
                    imagelinks.append(imageurl);
                    buffer=buffer.remove(imageurl);
                }
                buffer="";
            }
        }
        //We have parsed out all the links, so emit signal that we are ready for fetching of the pictures
        emit googlequeryready();
        disconnect(url,SIGNAL(requestFinished(int, bool)),this,SLOT(getpicturelist(int,bool)));
    }
}

void coverfinder2::fetchcoverlist()
{
    //start all the queries in Internet, and then just wait for incoming pictures
    QStringList::Iterator index=imagelinks.begin();
    covernumber=0;//set the counter to 0, and than count the pictures, so we know, if we still have to wait for some results
    while(index!=imagelinks.end())
    {
        getlink(*index);
        covernumber++;
        index++;
    }
}

void coverfinder2::getlink(QString link)
{
    //Split the link up into server and file, and than get the image
    QString server=link.right(link.length()-(link.find('.')+1));
    server=server.left(server.find('/'));
    //We have to throw away everything, until we reach the 3rd /-Sign
    QString file=link;
    for (int i=1;i<=2;i++)
        file=file.right(file.length()-(file.find('/')+1));
    file=file.right(file.length()-(file.find('/')));//keep the last /, but throw away everything in front
    QHttp *imagelink=new QHttp();
    imagelink->setHost(server,80);
    //Store the imagelink in a list with its transactionid
    linkitem *actuallookup=new linkitem();
    actuallookup->link=link;
    actuallookup->url=imagelink;
    actuallookup->transactionid=imagelink->get
                                (file);
    linklist.append(actuallookup);
    connect(imagelink,SIGNAL(requestFinished(int, bool)),SLOT(getfinished(int,bool)));
}

void coverfinder2::getfinished(int trid,bool error)
{
    //Find the right query, and  fetch all info before deleting the query
    if (!error)
    {
        QPtrList<linkitem>::Iterator index=linklist.begin();
        bool tridfound=FALSE;
        while(!tridfound&&(index!=linklist.end()))
        {
            if ((*index)->transactionid==trid)
                tridfound=TRUE;
            else
                index++;
        }
        //store the result into a Qimage and, than give that to the coverlayout
        if (tridfound)
        {
            QByteArray receiveddata=(*index)->url->readAll();
            QImage imagebuffer;
            if(imagebuffer.loadFromData(receiveddata))
            {
                emit newpicturereceived(imagebuffer);
            }
            else
            {
                cerr<<"No Picture here anymore"<<endl;
            }
        }
    }
    else
        cerr<<"Something went wrong with the http-request"<<endl;
}

void coverfinder2::addpicturetolayout(QImage imagebuffer)
{
    coverindex++;
    coverhelper2 *actualentry=new coverhelper2(coverselectorlayout);
    coverlist.append(actualentry);
    QString size=QString::number(imagebuffer.width())+"x"+QString::number(imagebuffer.height());
    actualentry->sizelabel->setText(size);
    //throw image in buffer onto the imagelist and create a button with it
    //since we want to have a smart layout, we resize the pictures to 100x100
    QImage scaledcover;
    actualentry->realpicture=imagebuffer.copy();
    scaledcover=imagebuffer.copy();
    scaledcover=scaledcover.smoothScale(80,80,QImage::ScaleMin);
    actualentry->coverpicture->setPixmap(scaledcover);
    radiogroup->insert(actualentry->coverradio,coverindex);
    actualentry->show();
    coverfinderlayout->adjustSize();
    coverselectorlayout->adjustSize();
    this->adjustSize();
}

void coverfinder2::cancelslot()
{
    emit abort();
}

void coverfinder2::okslot()
{
    QImage newpicture;
    //Check out, wich picture is selected, and load it into newpicture
    int number=radiogroup->selectedId();
    QPtrList<coverhelper2>::Iterator index=coverlist.begin();
    for (int i=1;i<number;i++)
        index++;
    newpicture=(*index)->realpicture.copy();
    QString size=QString::number(newpicture.width())+"x"+QString::number(newpicture.height());
    emit pictureselected(newpicture);
}

void coverfinder2::checkokslot(int selectedcover)
{
    if (selectedcover)
        okbutton->setEnabled(TRUE);
}

coverhelper2::coverhelper2(QWidget *motherwidget)
{
    covergroup=new QGroupBox(3,Qt::Horizontal,motherwidget);
    coverradio=new QRadioButton(covergroup);
    sizelabel=new QLabel(covergroup);
    coverpicture=new QLabel(covergroup);

}

coverhelper2::~coverhelper2()
{
    delete coverradio;
    delete sizelabel;
    delete coverpicture;
    delete covergroup;
}

void coverhelper2::show()
{
    covergroup->show();
    sizelabel->show();
    coverradio->show();
    coverpicture->show();
}
