/*******************************************************************************
 (c) 2005-2014 Copyright, Real-Time Innovations, Inc.  All rights reserved.
 RTI grants Licensee a license to use, modify, compile, and create derivative
 works of the Software.  Licensee has the right to distribute object form only
 for use with RTI products.  The Software is provided "as is", with no warranty
 of any type, including any warranty for fitness for any purpose. RTI is under
 no obligation to maintain or support the Software.  RTI shall not be liable for
 any incidental or consequential damages arising out of the use or inability to
 use the software.
 ******************************************************************************/
/* msg_publisher.c

   A publication of data of type msg

   This file is derived from code automatically generated by the rtiddsgen
   command:

   rtiddsgen -language C -example <arch> msg.idl

   Example publication of type msg automatically generated by
   'rtiddsgen'. To test them follow these steps:

   (1) Compile this file and the example subscription.

   (2) Start the subscription on the same domain used for RTI Data Distribution
       Service with the command
       objs/<arch>/msg_subscriber <domain_id> <sample_count>

   (3) Start the publication on the same domain used for RTI Data Distribution
       Service with the command
       objs/<arch>/msg_publisher <domain_id> <sample_count>

   (4) [Optional] Specify the list of discovery initial peers and
       multicast receive addresses via an environment variable or a file
       (in the current working directory) called NDDS_DISCOVERY_PEERS.

   You can run any number of publishers and subscribers programs, and can
   add and remove them dynamically from the domain.


   Example:

       To run the example application on domain <domain_id>:

       On Unix:

       objs/<arch>/msg_publisher <domain_id>
       objs/<arch>/msg_subscriber <domain_id>

       On Windows:

       objs\<arch>\msg_publisher <domain_id>
       objs\<arch>\msg_subscriber <domain_id>


modification history
------------ -------
* Add code to store keys of authorized participants

* Define listeners for builtin topics, which get called when
  we find a new participant or reader.

* Create disabled participant to ensure our listeners are installed
  before anything is processed

* Install listeners

* Do not ignore subscriber since it is a bad security practice.

* Print key and instance_handle info.
*/

#include "msg.h"
#include "msgSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>

/* Authorization string. */
const char *auth = "password";

/*
 * The builtin subscriber sets participant_qos.user_data and
 * so we set up listeners for the builtin
 *  DataReaders to access these fields.
 */

/* This gets called when a participant has been discovered */
void BuiltinParticipantListener_on_data_available(
        void *listener_data,
        DDS_DataReader *reader)
{
    DDS_ParticipantBuiltinTopicDataDataReader *builtin_reader = NULL;
    struct DDS_ParticipantBuiltinTopicDataSeq data_seq =
            DDS_SEQUENCE_INITIALIZER;
    struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
    DDS_ReturnCode_t retcode;

    int i;
    int len;
    int ih[6];

    builtin_reader = DDS_ParticipantBuiltinTopicDataDataReader_narrow(reader);

    /* We only process newly seen participants */
    retcode = DDS_ParticipantBuiltinTopicDataDataReader_take(
            builtin_reader,
            &data_seq,
            &info_seq,
            DDS_LENGTH_UNLIMITED,
            DDS_ANY_SAMPLE_STATE,
            DDS_NEW_VIEW_STATE,
            DDS_ANY_INSTANCE_STATE);

    /*
     * This happens when we get announcements from participants we
     * already know about
     */
    if (retcode == DDS_RETCODE_NO_DATA)
        return;

    if (retcode != DDS_RETCODE_OK) {
        printf("***Error: failed to access data from the built-in reader\n");
        return;
    }

    len = DDS_ParticipantBuiltinTopicDataSeq_get_length(&data_seq);
    for (i = 0; i < len; ++i) {
        struct DDS_SampleInfo *info = NULL;
        struct DDS_ParticipantBuiltinTopicData *data = NULL;
        char *participant_data = "nil";
        int is_auth = 0;

        info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
        data = DDS_ParticipantBuiltinTopicDataSeq_get_reference(&data_seq, i);

        if (!info->valid_data)
            continue;
        /* see if there is any participant_data */
        if (DDS_OctetSeq_get_length(&data->user_data.value) != 0) {
            /* This sequence is guaranteed to be contiguous */
            participant_data = (char *) (DDS_OctetSeq_get_reference(
                    &data->user_data.value,
                    0));
            is_auth = (strcmp(participant_data, auth) == 0);
        }

        printf("Built-in Reader: found participant \n");
        printf("\tkey->'%08x%08x%08x'\n\tuser_data->'%s'\n",
               data->key.value[0],
               data->key.value[1],
               data->key.value[2],
               participant_data);

        memcpy(ih, &info->instance_handle, sizeof(info->instance_handle));
        printf("instance_handle: %08x%08x %08x%08x %08x%08x \n",
               ih[0],
               ih[1],
               ih[2],
               ih[3],
               ih[4],
               ih[5]);

        /* Ignore unauthorized subscribers */
        if (!is_auth) {
            /* Get the associated participant... */
            DDS_DomainParticipant *participant = NULL;
            DDS_Subscriber *subscriber = NULL;

            subscriber = DDS_DataReader_get_subscriber(reader);
            participant = DDS_Subscriber_get_participant(subscriber);

            printf("Bad authorization, ignoring participant\n");

            /* Ignore the remote reader */
            DDS_DomainParticipant_ignore_participant(
                    participant,
                    &info->instance_handle);
        }
    }
    retcode = DDS_ParticipantBuiltinTopicDataDataReader_return_loan(
            builtin_reader,
            &data_seq,
            &info_seq);
    if (retcode != DDS_RETCODE_OK) {
        printf("return loan error %d\n", retcode);
    }
}

/* This gets called when a new subscriber has been discovered */
void BuiltinSubscriberListener_on_data_available(
        void *listener_data,
        DDS_DataReader *reader)
{
    DDS_SubscriptionBuiltinTopicDataDataReader *builtin_reader = NULL;
    struct DDS_SubscriptionBuiltinTopicDataSeq data_seq =
            DDS_SEQUENCE_INITIALIZER;
    struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
    DDS_ReturnCode_t retcode;

    int i;
    int len;
    int ih[6];

    builtin_reader = DDS_SubscriptionBuiltinTopicDataDataReader_narrow(reader);

    /* We only process newly seen subscribers */
    retcode = DDS_SubscriptionBuiltinTopicDataDataReader_take(
            builtin_reader,
            &data_seq,
            &info_seq,
            DDS_LENGTH_UNLIMITED,
            DDS_ANY_SAMPLE_STATE,
            DDS_NEW_VIEW_STATE,
            DDS_ANY_INSTANCE_STATE);

    if (retcode == DDS_RETCODE_NO_DATA)
        return;

    if (retcode != DDS_RETCODE_OK) {
        printf("***Error: failed to access data from the built-in reader\n");
        return;
    }

    len = DDS_SubscriptionBuiltinTopicDataSeq_get_length(&data_seq);
    for (i = 0; i < len; ++i) {
        struct DDS_SampleInfo *info = NULL;
        struct DDS_SubscriptionBuiltinTopicData *data = NULL;

        info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
        data = DDS_SubscriptionBuiltinTopicDataSeq_get_reference(&data_seq, i);

        if (!info->valid_data)
            continue;

        printf("Built-in Reader: found subscriber \n");
        printf("\tparticipant_key->'%08x%08x%08x'\n",
               data->participant_key.value[0],
               data->participant_key.value[1],
               data->participant_key.value[2]);

        printf("\tkey->'%08x %08x %08x'\n",
               data->key.value[0],
               data->key.value[1],
               data->key.value[2]);

        memcpy(ih, &info->instance_handle, sizeof(info->instance_handle));
        printf("instance_handle: %08x%08x %08x%08x %08x%08x \n",
               ih[0],
               ih[1],
               ih[2],
               ih[3],
               ih[4],
               ih[5]);
    }

    retcode = DDS_SubscriptionBuiltinTopicDataDataReader_return_loan(
            builtin_reader,
            &data_seq,
            &info_seq);
    if (retcode != DDS_RETCODE_OK) {
        printf("return loan error %d\n", retcode);
    }
}

/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
    DDS_ReturnCode_t retcode;
    int status = 0;

    if (participant != NULL) {
        retcode = DDS_DomainParticipant_delete_contained_entities(participant);
        if (retcode != DDS_RETCODE_OK) {
            printf("delete_contained_entities error %d\n", retcode);
            status = -1;
        }

        retcode = DDS_DomainParticipantFactory_delete_participant(
                DDS_TheParticipantFactory,
                participant);
        if (retcode != DDS_RETCODE_OK) {
            printf("delete_participant error %d\n", retcode);
            status = -1;
        }
    }

    /* RTI Data Distribution Service provides finalize_instance() method on
       domain participant factory forpeople who want to release memory used
       by the participant factory. Uncomment the following block of code for
       clean destruction of the singleton. */
    /*
    retcode = DDS_DomainParticipantFactory_finalize_instance();
    if (retcode != DDS_RETCODE_OK) {
        printf("finalize_instance error %d\n", retcode);
        status = -1;
     }
     */

    return status;
}

static int publisher_main(int domain_id, int sample_count)
{
    DDS_DomainParticipant *participant = NULL;
    DDS_Publisher *publisher = NULL;
    DDS_Topic *topic = NULL;
    DDS_DataWriter *writer = NULL;
    msgDataWriter *msg_writer = NULL;
    msg *instance = NULL;
    DDS_ReturnCode_t retcode;
    DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
    const char *type_name = NULL;
    int count = 0;
    struct DDS_Duration_t send_period = { 1, 0 };
    DDS_DataReader *builtin_participant_datareader = NULL;
    struct DDS_DataReaderListener builtin_participant_listener =
            DDS_DataReaderListener_INITIALIZER;
    DDS_DataReader *builtin_subscriber_datareader = NULL;
    struct DDS_DataReaderListener builtin_subscriber_listener =
            DDS_DataReaderListener_INITIALIZER;
    DDS_Subscriber *builtin_subscriber = NULL;
    /* struct DDS_DomainParticipantFactoryQos factory_qos =
            DDS_DomainParticipantFactoryQos_INITIALIZER;

    struct DDS_DomainParticipantQos participant_qos =
            DDS_DomainParticipantQos_INITIALIZER; */

    /* It is recommended to install built-in topic listeners on disabled
     * entities (EntityFactoryQoS). For this reason it is necessary to set
     * the autoenable_created_entities setting to false. To do this
     * programmatically, just uncomment the following code
     */

    /*
    retcode = DDS_DomainParticipantFactory_get_qos(DDS_TheParticipantFactory,
            &factory_qos);
    if (retcode != DDS_RETCODE_OK) {
        printf("Cannot get factory Qos for domain participant\n");
        return -1;
    }

    factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;

    switch(DDS_DomainParticipantFactory_set_qos(DDS_TheParticipantFactory,
            &factory_qos)) {
        case DDS_RETCODE_OK:
            break;
        case DDS_RETCODE_IMMUTABLE_POLICY: {
            printf("Cannot set factory Qos due to IMMUTABLE_POLICY");
            printf(" for domain participant\n");
            return -1;
            break;
        }
        case DDS_RETCODE_INCONSISTENT_POLICY: {
            printf("Cannot set factory Qos due to INCONSISTENT_POLICY ");
            printf("for domain participant\n");
            return -1;
            break;
        }
        default: {
            printf("Cannot set factory Qos for unknown reason for domain ");
            printf("participant\n");
            return -1;
            break;
        }
    }

    DDS_DomainParticipantFactoryQos_finalize(&factory_qos);
    */

    /* The maximum length for USER_DATA QoS field is set by default
       to 256 bytes. To increase it programmatically uncomment the
       following lines of code and replace DDS_PARTICIPANT_QOS_DEFAULT
       with participant_qos in the constructor call. */
    /*
    retcode = DDS_DomainParticipantFactory_get_default_participant_qos(
            DDS_TheParticipantFactory, &participant_qos);
    if (retcode != DDS_RETCODE_OK) {
        printf("get_default_participant_qos error\n");
        return -1;
    }

    participant_qos.resource_limits.participant_user_data_max_length = 1024;
    */

    /* To customize participant QoS, use
       the configuration file USER_QOS_PROFILES.xml */
    participant = DDS_DomainParticipantFactory_create_participant(
            DDS_TheParticipantFactory,
            domain_id,
            &DDS_PARTICIPANT_QOS_DEFAULT,
            NULL /* listener */,
            DDS_STATUS_MASK_NONE);
    if (participant == NULL) {
        printf("create_participant error\n");
        publisher_shutdown(participant);
        return -1;
    }

    /* Start changes for Builtin_Topics
     Installing listeners for the builtin topics requires several steps:
     */

    /*
     * First, get the builtin subscriber
     */
    builtin_subscriber =
            DDS_DomainParticipant_get_builtin_subscriber(participant);
    if (builtin_subscriber == NULL) {
        printf("***Error: failed to create builtin subscriber\n");
        return -1;
    }

    /*
     * Then get builtin subscriber's datareader for participants
     */
    builtin_participant_datareader = DDS_Subscriber_lookup_datareader(
            builtin_subscriber,
            DDS_PARTICIPANT_TOPIC_NAME);

    if (builtin_participant_datareader == NULL) {
        printf("***Error: failed to create builtin participant data reader\n");
        return -1;
    }

    /*
     * Install our listener in the builtin datareader
     */
    builtin_participant_listener.on_data_available =
            BuiltinParticipantListener_on_data_available;

    retcode = DDS_DataReader_set_listener(
            builtin_participant_datareader,
            &builtin_participant_listener,
            DDS_DATA_AVAILABLE_STATUS);
    if (retcode != DDS_RETCODE_OK) {
        printf("set_listener failed %d\n", retcode);
        return -1;
    }

    /*  Now we repeat the same procedure for builtin subscription topics. */

    /*
     *  Get builtin subscriber's datareader for subscribers
     */
    builtin_subscriber_datareader = DDS_Subscriber_lookup_datareader(
            builtin_subscriber,
            DDS_SUBSCRIPTION_TOPIC_NAME);

    if (builtin_subscriber_datareader == NULL) {
        printf("***Error: failed to create builtin subscription data reader\n");
        return -1;
    }

    /* Install our listener */
    builtin_subscriber_listener.on_data_available =
            BuiltinSubscriberListener_on_data_available;

    retcode = DDS_DataReader_set_listener(
            builtin_subscriber_datareader,
            &builtin_subscriber_listener,
            DDS_DATA_AVAILABLE_STATUS);
    if (retcode != DDS_RETCODE_OK) {
        printf("set_listener failed %d\n", retcode);
        return -1;
    }

    if (DDS_Entity_enable((DDS_Entity *) participant) != DDS_RETCODE_OK) {
        printf("***Error: Failed to Enable Participant\n");
        return -1;
    }


    /* To customize publisher QoS, use
       the configuration file USER_QOS_PROFILES.xml */
    publisher = DDS_DomainParticipant_create_publisher(
            participant,
            &DDS_PUBLISHER_QOS_DEFAULT,
            NULL /* listener */,
            DDS_STATUS_MASK_NONE);
    if (publisher == NULL) {
        printf("create_publisher error\n");
        publisher_shutdown(participant);
        return -1;
    }

    /* Register type before creating topic */
    type_name = msgTypeSupport_get_type_name();
    retcode = msgTypeSupport_register_type(participant, type_name);
    if (retcode != DDS_RETCODE_OK) {
        printf("register_type error %d\n", retcode);
        publisher_shutdown(participant);
        return -1;
    }

    /* To customize topic QoS, use
       the configuration file USER_QOS_PROFILES.xml */
    topic = DDS_DomainParticipant_create_topic(
            participant,
            "Example msg",
            type_name,
            &DDS_TOPIC_QOS_DEFAULT,
            NULL /* listener */,
            DDS_STATUS_MASK_NONE);
    if (topic == NULL) {
        printf("create_topic error\n");
        publisher_shutdown(participant);
        return -1;
    }

    /* To customize data writer QoS, use
       DDS_Publisher_get_default_datawriter_qos() */
    writer = DDS_Publisher_create_datawriter(
            publisher,
            topic,
            &DDS_DATAWRITER_QOS_DEFAULT,
            NULL /* listener */,
            DDS_STATUS_MASK_NONE);
    if (writer == NULL) {
        printf("create_datawriter error\n");
        publisher_shutdown(participant);
        return -1;
    }
    msg_writer = msgDataWriter_narrow(writer);
    if (msg_writer == NULL) {
        printf("DataWriter narrow error\n");
        publisher_shutdown(participant);
        return -1;
    }

    /* Create data sample for writing */
    instance = msgTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
    if (instance == NULL) {
        printf("msgTypeSupport_create_data error\n");
        publisher_shutdown(participant);
        return -1;
    }

    /* For a data type that has a key, if the same instance is going to be
       written multiple times, initialize the key here
       and register the keyed instance prior to writing */
    /*
    instance_handle = msgDataWriter_register_instance(
        msg_writer, instance);
    */

    /* Main loop */
    for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
        printf("Writing msg, count %d\n", count);

        /* Modify the data to be written here */
        instance->x = count;

        /* Write data */
        retcode = msgDataWriter_write(msg_writer, instance, &instance_handle);
        if (retcode != DDS_RETCODE_OK) {
            printf("write error %d\n", retcode);
        }

        NDDS_Utility_sleep(&send_period);
    }

    /*
    retcode = msgDataWriter_unregister_instance(
        msg_writer, instance, &instance_handle);
    if (retcode != DDS_RETCODE_OK) {
        printf("unregister instance error %d\n", retcode);
    }
    */

    /* Delete data sample */
    retcode = msgTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
    if (retcode != DDS_RETCODE_OK) {
        printf("msgTypeSupport_delete_data error %d\n", retcode);
    }

    /* Cleanup and delete delete all entities */
    return publisher_shutdown(participant);
}

int main(int argc, char *argv[])
{
    int domain_id = 0;
    int sample_count = 0; /* infinite loop */

    if (argc >= 2) {
        domain_id = atoi(argv[1]);
    }
    if (argc >= 3) {
        sample_count = atoi(argv[2]);
    }

    /* Uncomment this to turn on additional logging
    NDDS_Config_Logger_set_verbosity_by_category(
        NDDS_Config_Logger_get_instance(),
        NDDS_CONFIG_LOG_CATEGORY_API,
        NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
    */

    return publisher_main(domain_id, sample_count);
}
