#include "sampleImage.h"
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QEventLoop>
#include <QUrl>
#include <QThread>
#include <QApplication>

CImageResourceSample::CImageResourceSample()
:   m_imageDecodingThread( new CImageDecodingThreadSample )
  , m_decodingThread()
{
  m_imageDecodingThread.data()->moveToThread(&m_decodingThread);
  printf("Thread Started \n");
  m_decodingThread.start();
  QObject::connect(&m_decodingThread, SIGNAL(started()), m_imageDecodingThread.data(), SLOT(onStarted()));
  QObject::connect(m_imageDecodingThread.data(), SIGNAL(completed()), this, SLOT(mainThreadcomplete()));  
}

CImageResourceSample::~CImageResourceSample()
{

}
void CImageResourceSample::mainThreadcomplete()
{
 printf("Signal Received from image thread \n");
}
CImageResourceSample* CImageResourceSample::resource = NULL;

CImageResourceSample* CImageResourceSample::getInstance()
{
    if (resource == NULL)
    {
        resource = new CImageResourceSample();
    }
    printf("instance created\n");
    return resource;
}

CImageDecodingThreadSample::CImageDecodingThreadSample()
: m_manager(NULL)
{
} 
CImageDecodingThreadSample::~CImageDecodingThreadSample()
{

}
void CImageDecodingThreadSample::onStarted()
{
    m_manager.reset( new QNetworkAccessManager());
    m_timer = new QTimer();
    QObject::connect(m_manager.data(), SIGNAL(finished(QNetworkReply*)), this, SLOT(onReplyFinished(QNetworkReply*)));  
    m_timer->setInterval(500);
    QObject::connect(m_timer, SIGNAL(timeout()),this ,SLOT(startImageDownload()));
    m_timer->start();
    printf("instance Timer started \n");
    LoadImage("http://img.youtube.com/vi/bQVoAWSP7k4/0.jpg");

}

void CImageDecodingThreadSample::startImageDownload()
{
   printf("Time out received for image download\n\n");
    LoadImage("http://img.youtube.com/vi/bQVoAWSP7k4/0.jpg");
}
void CImageDecodingThreadSample::LoadImage(QString newUrl)
{
   m_url = newUrl;
   loadFromNetwork(m_url);
}

void CImageDecodingThreadSample::loadFromNetwork(QUrl url)
{
//  QUrl url(url);
  QNetworkRequest request(url);
  QNetworkReply *reply = m_manager->get(request);
  QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onReplyError(QNetworkReply::NetworkError)));
}

void CImageDecodingThreadSample::onReplyFinished(QNetworkReply *reply)
{
  emit completed();
  printf("Image reply finished slot \n"); 
}

void CImageDecodingThreadSample::onReplyError(QNetworkReply::NetworkError code)
{
    emit completed();
    printf("error code receiver %d \n",static_cast<int>( code ));
}


