/*
 * This RPC server 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 should subclass this implementation and define the required abstract methods to complete
 * implementing the interface. Note that there are several helper methods available to simplify
 * this task, or to retrieve more information about the caller.
 *
 * See the full RPC documentation for more details.
 */
#include "Server_Driverman.hpp"
#include "RpcHelpers_Driverman.hpp"

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

#include <rpc/rt/RpcIoStream.hpp>

using namespace rpc;

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
using Server = DrivermanServer;

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

/**
 * Releases any allocated resources.
 */
Server::~DrivermanServer() {
    free(this->txBuf);
}

/**
 * Continuously processes messages until processing fails to receive another message.
 */
bool Server::run(const bool block) {
    bool cont;
    do {
        cont = this->runOne(block);
    } while(cont);
    return cont;
}

/**
 * Reads a single message from the RPC connection and attempts to process it.
 *
 * @return Whether a message was able to be received and processed.
 */
bool Server::runOne(const bool block) {
    // try to receive message
    std::span<std::byte> buf;
    if(!this->io->receive(buf, block)) return false;

    // get the message header and its payload
    if(buf.size() < sizeof(MessageHeader)) {
        this->_HandleError(false, "Received message too small");
        return false;
    }
    const auto hdr = reinterpret_cast<const MessageHeader *>(buf.data());

    const auto payload = buf.subspan(offsetof(MessageHeader, payload));

    // then invoke the appropriate marshalling function
    switch(hdr->type) {
        case static_cast<uint64_t>(internals::Type::AddDevice):
            this->_marshallAddDevice(*hdr, payload);
            break;
        case static_cast<uint64_t>(internals::Type::SetDeviceProperty):
            this->_marshallSetDeviceProperty(*hdr, payload);
            break;
        case static_cast<uint64_t>(internals::Type::GetDeviceProperty):
            this->_marshallGetDeviceProperty(*hdr, payload);
            break;
        case static_cast<uint64_t>(internals::Type::StartDevice):
            this->_marshallStartDevice(*hdr, payload);
            break;
        case static_cast<uint64_t>(internals::Type::StopDevice):
            this->_marshallStopDevice(*hdr, payload);
            break;
        case static_cast<uint64_t>(internals::Type::Notify):
            this->_marshallNotify(*hdr, payload);
            break;
    }
    return true;
}


// Helper method to build and send a reply message
void Server::_sendReply(const MessageHeader &inHdr, const size_t payloadBytes) {
    const size_t len = sizeof(MessageHeader) + payloadBytes;

    auto hdr = reinterpret_cast<MessageHeader *>(this->txBuf);
    memset(hdr, 0, sizeof(*hdr));
    hdr->type = inHdr.type;
    hdr->flags = MessageHeader::Flags::Response;
    hdr->tag = inHdr.tag;

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

// Allocates an aligned transmit buffer of the given size
void Server::_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 server 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 Server::_HandleError(const bool fatal, const std::string_view &what) {
    fprintf(stderr, "[RPCS] %s: Encountered %s RPC error: %s\n", kServiceName.data(),
        fatal ? "fatal" : "recoverable", what.data());
    if(fatal) exit(-1);
}
/*
 * Autogenerated marshalling method for 'addDevice' (id $e2cd5678129683fe)
 * Have 2 parameter(s), 1 return(s); method is sync
 */
void Server::_marshallAddDevice(const MessageHeader &hdr, const std::span<std::byte> &payload) {
    internals::AddDeviceRequest request;
    if(!deserialize(payload, request)) return this->_HandleError(false, "Failed to deserialize request");

    auto retVal = this->implAddDevice(request.parent, request.driverId);

    internals::AddDeviceResponse reply;
    reply.path = retVal;

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

    auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
    std::span<std::byte> data(packet->payload, numBytes);
    if(!serialize(data, reply)) return this->_HandleError(false, "Failed to serialize reply");

    this->_sendReply(hdr, numBytes);
}
/*
 * Autogenerated marshalling method for 'SetDeviceProperty' (id $4fe09a246da305bc)
 * Have 3 parameter(s), 1 return(s); method is sync
 */
void Server::_marshallSetDeviceProperty(const MessageHeader &hdr, const std::span<std::byte> &payload) {
    internals::SetDevicePropertyRequest request;
    if(!deserialize(payload, request)) return this->_HandleError(false, "Failed to deserialize request");

    auto retVal = this->implSetDeviceProperty(request.path, request.key, request.data);

    internals::SetDevicePropertyResponse reply;
    reply.status = retVal;

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

    auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
    std::span<std::byte> data(packet->payload, numBytes);
    if(!serialize(data, reply)) return this->_HandleError(false, "Failed to serialize reply");

    this->_sendReply(hdr, numBytes);
}
/*
 * Autogenerated marshalling method for 'GetDeviceProperty' (id $faac446645be5520)
 * Have 2 parameter(s), 2 return(s); method is sync
 */
void Server::_marshallGetDeviceProperty(const MessageHeader &hdr, const std::span<std::byte> &payload) {
    internals::GetDevicePropertyRequest request;
    if(!deserialize(payload, request)) return this->_HandleError(false, "Failed to deserialize request");

    auto retVal = this->implGetDeviceProperty(request.path, request.key);

    internals::GetDevicePropertyResponse reply;
    reply.status = retVal.status;
    reply.data = retVal.data;

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

    auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
    std::span<std::byte> data(packet->payload, numBytes);
    if(!serialize(data, reply)) return this->_HandleError(false, "Failed to serialize reply");

    this->_sendReply(hdr, numBytes);
}
/*
 * Autogenerated marshalling method for 'StartDevice' (id $6a7cbf9e2efa75f0)
 * Have 1 parameter(s), 1 return(s); method is sync
 */
void Server::_marshallStartDevice(const MessageHeader &hdr, const std::span<std::byte> &payload) {
    internals::StartDeviceRequest request;
    if(!deserialize(payload, request)) return this->_HandleError(false, "Failed to deserialize request");

    auto retVal = this->implStartDevice(request.path);

    internals::StartDeviceResponse reply;
    reply.status = retVal;

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

    auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
    std::span<std::byte> data(packet->payload, numBytes);
    if(!serialize(data, reply)) return this->_HandleError(false, "Failed to serialize reply");

    this->_sendReply(hdr, numBytes);
}
/*
 * Autogenerated marshalling method for 'StopDevice' (id $ee8b158787490a80)
 * Have 1 parameter(s), 1 return(s); method is sync
 */
void Server::_marshallStopDevice(const MessageHeader &hdr, const std::span<std::byte> &payload) {
    internals::StopDeviceRequest request;
    if(!deserialize(payload, request)) return this->_HandleError(false, "Failed to deserialize request");

    auto retVal = this->implStopDevice(request.path);

    internals::StopDeviceResponse reply;
    reply.status = retVal;

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

    auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
    std::span<std::byte> data(packet->payload, numBytes);
    if(!serialize(data, reply)) return this->_HandleError(false, "Failed to serialize reply");

    this->_sendReply(hdr, numBytes);
}
/*
 * Autogenerated marshalling method for 'Notify' (id $63ce1044c4349828)
 * Have 2 parameter(s), 1 return(s); method is sync
 */
void Server::_marshallNotify(const MessageHeader &hdr, const std::span<std::byte> &payload) {
    internals::NotifyRequest request;
    if(!deserialize(payload, request)) return this->_HandleError(false, "Failed to deserialize request");

    auto retVal = this->implNotify(request.path, request.key);

    internals::NotifyResponse reply;
    reply.status = retVal;

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

    auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
    std::span<std::byte> data(packet->payload, numBytes);
    if(!serialize(data, reply)) return this->_HandleError(false, "Failed to serialize reply");

    this->_sendReply(hdr, numBytes);
}
#pragma clang diagnostic pop
