#include "ProducerExample.h"

#include <fstream>
#include <Pacpus/kernel/ComponentFactory.h>
#include <Pacpus/kernel/ComponentManager.h>
#include <Pacpus/kernel/InputOutputInterface.h>
#include <Pacpus/kernel/Log.h>
#include <QColor>

using namespace pacpus;
using namespace std;

DECLARE_STATIC_LOGGER("pacpus.cityvip.test.ProducerExample");

/// Construct the factory
static ComponentFactory<ProducerExample> sFactory("ProducerExample");

static const char * outputFileName = "producer.txt";

ProducerExample::ProducerExample(QString name)
    : ComponentBase(name)
{
    LOG_TRACE("constructor(" << name << ")");
}

ProducerExample::~ProducerExample()
{
    LOG_TRACE("destructor");
}

ComponentBase::COMPONENT_CONFIGURATION
ProducerExample::configureComponent(XmlComponentConfig /*config*/)
{
    LOG_TRACE(Q_FUNC_INFO);

    LOG_INFO("component '" << name() << "' configured");
    return ComponentBase::CONFIGURED_OK;
}
    
void ProducerExample::addInputs()
{
    // empty: no inputs
}

void ProducerExample::addOutputs()
{
    addOutput<QImage, ProducerExample>("image");
}

void ProducerExample::startActivity()
{
    LOG_TRACE(Q_FUNC_INFO);

    //Q_ASSERT(input);

    start();
    setActive(true);
    setState(MONITOR_OK);
    LOG_INFO("started component '" << name() << "'");
}

void ProducerExample::stopActivity()
{
    LOG_TRACE(Q_FUNC_INFO);

    setActive(false);
    setState(STOPPED);
    LOG_INFO("stopped component '" << name() << "'");
}

void ProducerExample::run()
{
    unsigned int counter = 1;
    int waitTimeMicros = 150 * 1000;

    std::fstream file(outputFileName, std::ios_base::out | std::ios_base::app);
    if (!file.is_open()) {
        LOG_ERROR("file '" << outputFileName << "'cannot be opened");
    }

    QImage mat(10000, 1000, QImage::Format_RGB32);
    //mat.fill( qRgb(189, 149, 39));

    OutputInterface<QImage, ProducerExample> * imageOutput = 
        getTypedOutput<QImage, ProducerExample>("image");

    while (isActive()) {
        //mat.setPixel(0,0,i);
        LOG_INFO("Sent QImage: "
            << "size = " << mat.size().width()<< " x " << mat.size().height()
            );

        if (imageOutput && imageOutput->hasConnection()) {
            imageOutput->send(mat);
        }

        LOG_INFO("Sent data=" << counter << ", time=" << road_time());
        file << counter << " " << road_time() << "\n" << std::flush;

        usleep(waitTimeMicros);
        ++counter;
        setState(MONITOR_OK);
    }

    file.close();
}
