// Copyright 2014 Open Source Robotics Foundation, Inc.
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <chrono>
#include <cstdio>
#include <memory>
#include <utility>

#include "rclcpp_dds/rclcpp_dds.hpp"

#include "rclcpp_components/register_node_macro.hpp"

#include "rclcpp_dds_examples/visibility_control.h"

// Include type support code generated by rtiddsgen
#include "std_msgs/msg/String.hpp"


namespace rclcpp_dds_examples
{
// Create a Talker class that subclasses the generic rclcpp::Node base class.
// The main function below will instantiate the class as a ROS node.
// Use Connext's Modern C++ API to create a DataWriter to publish messages.
class DdsTalker : public rclcpp_dds::DDSNode
{
public:
  RCLCPP_DDS_EXAMPLES_PUBLIC
  explicit DdsTalker(const rclcpp::NodeOptions & options)
  : DDSNode("talker", options)
  {
    // Create a function for when messages are to be sent.
    setvbuf(stdout, NULL, _IONBF, BUFSIZ);
    auto publish_message =
      [this]() -> void
      {
        std_msgs::msg::String msg("Hello World: " + std::to_string(count_++));
        RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", msg.data().c_str());
        writer_.write(msg);
      };
    auto writer_qos = this->get_default_datawriter_qos();
    writer_qos << dds::core::policy::Reliability::Reliable();
    writer_qos << dds::core::policy::History::KeepLast(7);
    writer_ = this->create_datawriter<std_msgs::msg::String>("chatter", writer_qos);
    // Use a timer to schedule periodic message publishing.
    using namespace std::chrono_literals;
    timer_ = this->create_wall_timer(1s, publish_message);
  }

private:
  size_t count_ = 1;
  dds::pub::DataWriter<std_msgs::msg::String> writer_{nullptr};
  rclcpp::TimerBase::SharedPtr timer_;
};

}  // namespace rclcpp_dds_examples

RCLCPP_COMPONENTS_REGISTER_NODE(rclcpp_dds_examples::DdsTalker)
