#ifndef PACKET_H
#define PACKET_H

#include <game.h>
#include <net.h>
#include <stdbool.h>
#include <stddef.h>

#ifdef __cplusplus
extern "C"
{
#endif

union packet
{
    struct packet_common
    {
        enum packet_type
        {
            PACKET_TYPE_NAME,
            PACKET_TYPE_CHAT,
            PACKET_TYPE_READY,

            MAX_PACKET_TYPES
        } type;
    } common;

    struct packet_name
    {
        struct packet_common common;
        const char *name;
    } name;

    struct packet_chat
    {
        struct packet_common common;
        const char *msg;
    } chat;

    struct packet_ready
    {
        struct packet_common common;
        bool ready;
    } ready;
};

enum {PACKET_MAX_MESSAGE_LEN = 64};

struct packet_ctx
{
    struct net_host *host;
    void (*cb)(net_peer, const union packet *, void *);
    void *arg;
};

struct packet_input
{
    union packet p;
    size_t body_i;

    enum
    {
        PACKET_STATE_HEADER,
        PACKET_STATE_BODY
    } state;

    union packet_data
    {
        struct packet_ctx_name
        {
            size_t len;
            char name[GAME_PLAYER_NAME_LEN];
        } name;

        struct packet_ctx_chat
        {
            size_t len;
            char msg[PACKET_MAX_MESSAGE_LEN];
        } chat;
    } data;
};

int packet_send(const struct packet_ctx *h, net_peer peer, const union packet *pkt);
int packet_feed(const struct packet_ctx *h, net_peer p,
    struct packet_input *in, const void *buf, size_t n);

#ifdef __cplusplus
}
#endif

#endif /* PACKET_H */
