/*
 * This RPC server stub was autogenerated by idlc (version c8601c6e). DO NOT EDIT!
 * Generated from WindowServer.idl for interface WindowServer at 2021-07-11T18:46:48-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_WindowServer.hpp"
#include "RpcHelpers_WindowServer.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 = WindowServerServer;

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

/**
 * Releases any allocated resources.
 */
Server::~WindowServerServer() {
    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::SubmitKeyEvent):
            this->_marshallSubmitKeyEvent(*hdr, payload);
            break;
        case static_cast<uint64_t>(internals::Type::SubmitMouseEvent):
            this->_marshallSubmitMouseEvent(*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 'SubmitKeyEvent' (id $5313353be07b5c96)
 * Have 2 parameter(s), 0 return(s); method is async
 */
void Server::_marshallSubmitKeyEvent(const MessageHeader &hdr, const std::span<std::byte> &payload) {
    internals::SubmitKeyEventRequest request;
    if(!deserialize(payload, request)) return this->_HandleError(false, "Failed to deserialize request");

    this->implSubmitKeyEvent(request.scancode, request.release);
}
/*
 * Autogenerated marshalling method for 'SubmitMouseEvent' (id $46e5a95b9576c0c)
 * Have 4 parameter(s), 0 return(s); method is async
 */
void Server::_marshallSubmitMouseEvent(const MessageHeader &hdr, const std::span<std::byte> &payload) {
    internals::SubmitMouseEventRequest request;
    if(!deserialize(payload, request)) return this->_HandleError(false, "Failed to deserialize request");

    this->implSubmitMouseEvent(request.buttons, request.dX, request.dY, request.dZ);
}
#pragma clang diagnostic pop
