/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 "common/wrapper.h"
#include "common/util.h"
#include "rpc/rpc_engine.h"
#include <asio/ip/tcp.hpp>

using namespace ::hdfs;
using ::asio::ip::tcp;

RpcEngine * RpcEngine_create(IoServiceImpl * io_service,
                             std::string client_name, std::string protocol,
                             int version) {
  RpcEngine *engine = new RpcEngine(&io_service->io_service(), client_name,
                                    protocol.c_str(), version);
  return engine;
}

std::string RpcEngine_connect(RpcEngine* self, std::string host, int port) {
  tcp::endpoint ep(asio::ip::address::from_string(host), port);
  std::vector<tcp::endpoint> server(1, ep);
  Status status = self->Connect(server);
  return status.ToString();
}

void RpcEngine_start(RpcEngine *self) {
  self->Start();
}

std::string RpcEngine_rpc(RpcEngine *self, std::string method,
                          std::string request, std::string status) {
  auto response = std::make_shared<std::string>();
  Status stat = self->RawRpc(method, std::move(request), response);
  if (!stat.ok()) {
    printf(("[ERR]" + stat.ToString()).c_str());
    return nullptr;
  }
  std::string resp = response.get()->c_str();
  return resp;
}

void RpcEngine_destroy(RpcEngine * handle) {
  delete handle;
}
