/*
 * This RPC client stub was autogenerated by idlc (version 8a02fc5d). DO NOT EDIT!
 * Generated from Driverman.idl for interface Driverman at 2021-06-26T17:21:35-0500
 *
 * You may use these generated stubs directly as the RPC interface, or you can subclass it to
 * override the behavior of the function calls, or to perform some preprocessing to the data as
 * needed before sending it.
 *
 * See the full RPC documentation for more details.
 */
#include "Client_Driverman.hpp"
#include "RpcHelpers_Driverman.hpp"

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <rpc/rt/RpcIoStream.hpp>

using namespace rpc;

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
using Client = DrivermanClient;

/**
 * Creates a new client instance, with the given IO stream.
 */
Client::DrivermanClient(const std::shared_ptr<IoStream> &stream) : io(stream) {
}

/**
 * Shuts down the RPC client, releasing any allocated resources.
 */
Client::~DrivermanClient() {
    free(this->txBuf);
}

/// Sends the message that's been built up in the transmit message buffer.
uint32_t Client::_sendRequest(const uint64_t type, const size_t payloadBytes) {
    const size_t len = sizeof(MessageHeader) + payloadBytes;

    const auto tag = __atomic_add_fetch(&this->nextTag, 1, __ATOMIC_RELAXED);
    auto hdr = reinterpret_cast<MessageHeader *>(this->txBuf);
    memset(hdr, 0, sizeof(*hdr));
    hdr->type = type;
    hdr->flags = MessageHeader::Flags::Request;
    hdr->tag = tag;

    const std::span<std::byte> txBufSpan(reinterpret_cast<std::byte *>(this->txBuf), len);
    if(!this->io->sendRequest(txBufSpan)) {
        this->_HandleError(true, "Failed to send RPC request");
        return 0;
    }

    return tag;
}

// Allocates an aligned transmit buffer of the given size
void Client::_ensureTxBuf(const size_t payloadBytes) {
    const size_t len = sizeof(MessageHeader) + payloadBytes + 16;
    if(len > this->txBufSize) {
        free(this->txBuf);
        int err = posix_memalign(&this->txBuf, 16, len);
        if(err) {
            return this->_HandleError(true, "Failed to allocate RPC send buffer");
        }
        this->txBufSize = len;
    }
}

/**
 * Handles an error that occurred on the client connection. Implementations may override this
 * method if they want to use exceptions, for example.
 *
 * @param fatal If set, the error precludes further operation on this RPC connection
 * @param what Descriptive string for the error
 */
void Client::_HandleError(const bool fatal, const std::string_view &what) {
    fprintf(stderr, "[RPCC] %s: Encountered %s RPC error: %s\n", kServiceName.data(),
        fatal ? "fatal" : "recoverable", what.data());
    if(fatal) exit(-1);
}
/*
 * Autogenerated call method for 'addDevice' (id $e2cd5678129683fe)
 * Have 2 parameter(s), 1 return(s); method is sync
 */
std::string Client::AddDevice(const std::string &parent, const std::string &driverId) {
    uint32_t sentTag;
    {
        internals::AddDeviceRequest request;
        request.parent = parent;
        request.driverId = driverId;

        const auto numBytes = bytesFor(request);
        this->_ensureTxBuf(numBytes);

        auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
        std::span<std::byte> data(packet->payload, numBytes);
        serialize(data, request);
        sentTag = this->_sendRequest(static_cast<uint64_t>(internals::Type::AddDevice), numBytes);
    }
    {
        std::span<std::byte> buf;
        if(!this->io->receiveReply(buf)) this->_HandleError(false, "Failed to receive RPC reply");
        if(buf.size() < sizeof(MessageHeader)) this->_HandleError(false, "Received message too small");
        const auto hdr = reinterpret_cast<const MessageHeader *>(buf.data());
        if(hdr->tag != sentTag) this->_HandleError(false, "Invalid tag in reply RPC packet");
        else if(hdr->type != static_cast<uint64_t>(internals::Type::AddDevice)) this->_HandleError(false, "Invalid type in reply RPC packet");
        const auto payload = buf.subspan(offsetof(MessageHeader, payload));

        internals::AddDeviceResponse reply;
        if(!deserialize(payload, reply)) this->_HandleError(false, "Failed to decode message");
        return reply.path;
    }
}
/*
 * Autogenerated call method for 'SetDeviceProperty' (id $4fe09a246da305bc)
 * Have 3 parameter(s), 1 return(s); method is sync
 */
int32_t Client::SetDeviceProperty(const std::string &path, const std::string &key, const std::vector<std::byte> &data) {
    uint32_t sentTag;
    {
        internals::SetDevicePropertyRequest request;
        request.path = path;
        request.key = key;
        request.data = data;

        const auto numBytes = bytesFor(request);
        this->_ensureTxBuf(numBytes);

        auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
        std::span<std::byte> data(packet->payload, numBytes);
        serialize(data, request);
        sentTag = this->_sendRequest(static_cast<uint64_t>(internals::Type::SetDeviceProperty), numBytes);
    }
    {
        std::span<std::byte> buf;
        if(!this->io->receiveReply(buf)) this->_HandleError(false, "Failed to receive RPC reply");
        if(buf.size() < sizeof(MessageHeader)) this->_HandleError(false, "Received message too small");
        const auto hdr = reinterpret_cast<const MessageHeader *>(buf.data());
        if(hdr->tag != sentTag) this->_HandleError(false, "Invalid tag in reply RPC packet");
        else if(hdr->type != static_cast<uint64_t>(internals::Type::SetDeviceProperty)) this->_HandleError(false, "Invalid type in reply RPC packet");
        const auto payload = buf.subspan(offsetof(MessageHeader, payload));

        internals::SetDevicePropertyResponse reply;
        if(!deserialize(payload, reply)) this->_HandleError(false, "Failed to decode message");
        return reply.status;
    }
}
/*
 * Autogenerated call method for 'GetDeviceProperty' (id $faac446645be5520)
 * Have 2 parameter(s), 2 return(s); method is sync
 */
Client::GetDevicePropertyReturn Client::GetDeviceProperty(const std::string &path, const std::string &key) {
    uint32_t sentTag;
    {
        internals::GetDevicePropertyRequest request;
        request.path = path;
        request.key = key;

        const auto numBytes = bytesFor(request);
        this->_ensureTxBuf(numBytes);

        auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
        std::span<std::byte> data(packet->payload, numBytes);
        serialize(data, request);
        sentTag = this->_sendRequest(static_cast<uint64_t>(internals::Type::GetDeviceProperty), numBytes);
    }
    {
        std::span<std::byte> buf;
        if(!this->io->receiveReply(buf)) this->_HandleError(false, "Failed to receive RPC reply");
        if(buf.size() < sizeof(MessageHeader)) this->_HandleError(false, "Received message too small");
        const auto hdr = reinterpret_cast<const MessageHeader *>(buf.data());
        if(hdr->tag != sentTag) this->_HandleError(false, "Invalid tag in reply RPC packet");
        else if(hdr->type != static_cast<uint64_t>(internals::Type::GetDeviceProperty)) this->_HandleError(false, "Invalid type in reply RPC packet");
        const auto payload = buf.subspan(offsetof(MessageHeader, payload));

        internals::GetDevicePropertyResponse reply;
        if(!deserialize(payload, reply)) this->_HandleError(false, "Failed to decode message");
        GetDevicePropertyReturn r;
        r.status =  reply.status;
        r.data =  reply.data;
        return r;

    }
}
/*
 * Autogenerated call method for 'StartDevice' (id $6a7cbf9e2efa75f0)
 * Have 1 parameter(s), 1 return(s); method is sync
 */
int32_t Client::StartDevice(const std::string &path) {
    uint32_t sentTag;
    {
        internals::StartDeviceRequest request;
        request.path = path;

        const auto numBytes = bytesFor(request);
        this->_ensureTxBuf(numBytes);

        auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
        std::span<std::byte> data(packet->payload, numBytes);
        serialize(data, request);
        sentTag = this->_sendRequest(static_cast<uint64_t>(internals::Type::StartDevice), numBytes);
    }
    {
        std::span<std::byte> buf;
        if(!this->io->receiveReply(buf)) this->_HandleError(false, "Failed to receive RPC reply");
        if(buf.size() < sizeof(MessageHeader)) this->_HandleError(false, "Received message too small");
        const auto hdr = reinterpret_cast<const MessageHeader *>(buf.data());
        if(hdr->tag != sentTag) this->_HandleError(false, "Invalid tag in reply RPC packet");
        else if(hdr->type != static_cast<uint64_t>(internals::Type::StartDevice)) this->_HandleError(false, "Invalid type in reply RPC packet");
        const auto payload = buf.subspan(offsetof(MessageHeader, payload));

        internals::StartDeviceResponse reply;
        if(!deserialize(payload, reply)) this->_HandleError(false, "Failed to decode message");
        return reply.status;
    }
}
/*
 * Autogenerated call method for 'StopDevice' (id $ee8b158787490a80)
 * Have 1 parameter(s), 1 return(s); method is sync
 */
int32_t Client::StopDevice(const std::string &path) {
    uint32_t sentTag;
    {
        internals::StopDeviceRequest request;
        request.path = path;

        const auto numBytes = bytesFor(request);
        this->_ensureTxBuf(numBytes);

        auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
        std::span<std::byte> data(packet->payload, numBytes);
        serialize(data, request);
        sentTag = this->_sendRequest(static_cast<uint64_t>(internals::Type::StopDevice), numBytes);
    }
    {
        std::span<std::byte> buf;
        if(!this->io->receiveReply(buf)) this->_HandleError(false, "Failed to receive RPC reply");
        if(buf.size() < sizeof(MessageHeader)) this->_HandleError(false, "Received message too small");
        const auto hdr = reinterpret_cast<const MessageHeader *>(buf.data());
        if(hdr->tag != sentTag) this->_HandleError(false, "Invalid tag in reply RPC packet");
        else if(hdr->type != static_cast<uint64_t>(internals::Type::StopDevice)) this->_HandleError(false, "Invalid type in reply RPC packet");
        const auto payload = buf.subspan(offsetof(MessageHeader, payload));

        internals::StopDeviceResponse reply;
        if(!deserialize(payload, reply)) this->_HandleError(false, "Failed to decode message");
        return reply.status;
    }
}
/*
 * Autogenerated call method for 'Notify' (id $63ce1044c4349828)
 * Have 2 parameter(s), 1 return(s); method is sync
 */
int32_t Client::Notify(const std::string &path, uint64_t key) {
    uint32_t sentTag;
    {
        internals::NotifyRequest request;
        request.path = path;
        request.key = key;

        const auto numBytes = bytesFor(request);
        this->_ensureTxBuf(numBytes);

        auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
        std::span<std::byte> data(packet->payload, numBytes);
        serialize(data, request);
        sentTag = this->_sendRequest(static_cast<uint64_t>(internals::Type::Notify), numBytes);
    }
    {
        std::span<std::byte> buf;
        if(!this->io->receiveReply(buf)) this->_HandleError(false, "Failed to receive RPC reply");
        if(buf.size() < sizeof(MessageHeader)) this->_HandleError(false, "Received message too small");
        const auto hdr = reinterpret_cast<const MessageHeader *>(buf.data());
        if(hdr->tag != sentTag) this->_HandleError(false, "Invalid tag in reply RPC packet");
        else if(hdr->type != static_cast<uint64_t>(internals::Type::Notify)) this->_HandleError(false, "Invalid type in reply RPC packet");
        const auto payload = buf.subspan(offsetof(MessageHeader, payload));

        internals::NotifyResponse reply;
        if(!deserialize(payload, reply)) this->_HandleError(false, "Failed to decode message");
        return reply.status;
    }
}
#pragma clang diagnostic pop
