//
// C++ Implementation: c6photoretriever
//
// Description: 
//
//
// Author: Giorgio Alfarano <openc6@hotmail.com>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "c6photoretriever.h"
#include "c6httpconnection.h"
#include "c6settings.h"
#include <qstring.h>
#include <vector>

static const QString PICTURE_EXT = ",c00.jpg";
std::vector<C6HttpConnection*> httpConnectionPool;

PhotoListEvent::PhotoListEvent(QStringList const& photoList): QEvent(QEvent::User)
        ,_photoList(new QStringList(photoList))      
{
}      

PhotoListEvent::~PhotoListEvent()
{
    delete _photoList;   
} 
const QStringList& PhotoListEvent::getPhotoList() const
{
    return(*_photoList);  
}  

C6PhotoRetriever::C6PhotoRetriever()
{
}

bool C6PhotoRetriever::event(QEvent * e)
{
    PhotoListEvent* event = dynamic_cast<PhotoListEvent*>(e);   
    if (event != 0)
    {  
        const QStringList& photoList = event->getPhotoList();
        for (unsigned int i=0; i < photoList.count(); i++)
        {
            requestPictureFromWeb(photoList[i]);      
        }             
    }
    
    return true;  
}     

void C6PhotoRetriever::requestPictureFromWeb(QString const& nick)
{
    QString myRequestUrl =C6Settings::getInstance().getPictureUrl();
    myRequestUrl+=nick+PICTURE_EXT;
  
    C6HttpConnection* httpData = new C6HttpConnection(myRequestUrl);
    httpConnectionPool.push_back(httpData);   
    
    connect(httpData,SIGNAL(bufferFull(const QString&,C6HttpConnection*)),SLOT(requestPictureDone(const QString&,C6HttpConnection*)));
    connect(httpData,SIGNAL(closed()),SLOT(requestPictureClose()));   
    httpData->get();
}

void C6PhotoRetriever::requestPictureDone(const QString& filename,C6HttpConnection* httpConnection)
{
    std::vector<C6HttpConnection*>::iterator it;
                
    for(it = httpConnectionPool.begin() ; it != httpConnectionPool.end(); it++)
    {
        if (*it == httpConnection)
        {
            QByteArray data = (*it)->getBuffer().copy();
           
            emit photoReady(data,filename);    
            
            (*it)->deleteLater();  
            httpConnectionPool.erase(it);        
            break;            
        }              
    }                     
}      

void C6PhotoRetriever::requestPictureClose()
{
}    

#include "c6photoretriever.moc"
