#include "AQTSampleMachinePlug.hpp"
#include <QDebug>
#include <fastdds/dds/domain/DomainParticipantFactory.hpp>
#include "HelloWorld.hpp"
#include "HelloWorldPubSubTypes.hpp"

AQTSampleMachinePlug::AQTSampleMachinePlug(QObject *parent)
    : QObject(parent)
    , participant_(nullptr)
    , publisher_(nullptr)
    , topic_(nullptr)
    , writer_(nullptr)
    , message_index_(0)
{
    type_ = TypeSupport(new HelloWorldPubSubType());
}

AQTSampleMachinePlug::~AQTSampleMachinePlug()
{
    if (writer_ != nullptr) {
        publisher_->delete_datawriter(writer_);
    }
    if (topic_ != nullptr) {
        participant_->delete_topic(topic_);
    }
    if (publisher_ != nullptr) {
        participant_->delete_publisher(publisher_);
    }
    if (participant_ != nullptr) {
        DomainParticipantFactory::get_instance()->delete_participant(participant_);
    }
}

bool AQTSampleMachinePlug::init()
{
    DomainParticipantQos participantQos;
    participantQos.name("Participant_publisher");
    participant_ = DomainParticipantFactory::get_instance()->create_participant(0, participantQos);

    if (participant_ == nullptr) {
        return false;
    }

    type_.register_type(participant_);

    publisher_ = participant_->create_publisher(PUBLISHER_QOS_DEFAULT);
    if (publisher_ == nullptr) {
        return false;
    }

    topic_ = participant_->create_topic(
        "HelloWorldTopic",
        "HelloWorld",
        TOPIC_QOS_DEFAULT);

    if (topic_ == nullptr) {
        return false;
    }

    writer_ = publisher_->create_datawriter(
        topic_,
        DATAWRITER_QOS_DEFAULT);

    if (writer_ == nullptr) {
        return false;
    }

    return true;
}

void AQTSampleMachinePlug::publishOnce()
{
    HelloWorld st;
    st.index(message_index_);
    st.message("Hello World " + std::to_string(message_index_));

    writer_->write(&st);

    emit messagePublished(QString::fromStdString(st.message()), message_index_);
    
    message_index_++;
}

QString AQTSampleMachinePlug::echo(const QString& message)
{
    return QString("Plugin Echo: %1").arg(message);
}

int AQTSampleMachinePlug::calculate(int a, int b)
{
    return a + b;
} 
