/*
本程序用于创建客户端节点,并调用服务端提供的服务接口，发送请求并处理响应。
*/

#include "rclcpp/rclcpp.hpp"
#include "cpp_prococol/srv/position.hpp"
#include <chrono>

using Positon = cpp_prococol::srv::Position;

class cppClientService : public rclcpp::Node
{
public:
    // 构造函数，创建客户端对象
    cppClientService() : Node("cpp_client_service")
    {
        client_ = this->create_client<Positon>("position");
    }

    // 发送请求的函数
    void send_request()
    {
        // 等待服务端准备就绪
        while (!client_->wait_for_service(std::chrono::seconds(1)))
        {
            if (!rclcpp::ok())
            {
                RCLCPP_ERROR(this->get_logger(), "Interrupted while waiting for the service. Exiting.");
                return;
            }
            RCLCPP_INFO(this->get_logger(), "Waiting for service to be available...");
        }

        // 构建请求体
        auto request = std::make_shared<Positon::Request>();
        request->target_x = 1.0;
        request->target_y = 2.0;

        // 定义处理响应的回调函数
        auto res_callback = [this](rclcpp::Client<Positon>::SharedFuture future)
        {
            auto res = future.get();
            if (res->result == Positon::Response::SUCCESS)
            {
                RCLCPP_INFO(this->get_logger(), "Service call succeeded: target position is valid.");
            }
            else
            {
                RCLCPP_WARN(this->get_logger(), "Service call failed: target position is invalid.");
            }
        };

        // 发送请求体并处理响应
        auto res = client_->async_send_request(request, res_callback);
    }

private:
    // 声明客户端对象
    rclcpp::Client<Positon>::SharedPtr client_;
};

int main(int argc, char **argv)
{
    rclcpp::init(argc, argv);

    auto node = std::make_shared<cppClientService>();
    node->send_request();

    rclcpp::spin(node);
    rclcpp::shutdown();
}