#ifndef NET_H
#define NET_H

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

#ifdef __cplusplus
extern "C"
{
#endif

enum net_domain
{
    NET_DOMAIN_IPV4,
    NET_DOMAIN_SERIAL
};

enum net_role
{
    NET_ROLE_SERVER,
    NET_ROLE_CLIENT
};

typedef void *net_peer;

struct net_event
{
    void (*connected)(net_peer p, void *arg);
    void (*disconnected)(net_peer p, void *arg);
    void (*received)(net_peer p, const void *buf, size_t n, void *arg);
    void *arg;
};

union net_connect
{
    struct net_connect_common
    {
        enum net_domain domain;
        struct net_event ev;
    } common;

    struct net_connect_ipv4
    {
        struct net_connect_common common;
        const char *addr;
        short port;
    } ipv4;

    struct net_connect_serial
    {
        struct net_connect_common common;

        struct net_serial_cfg
        {
            const char *dev;
            unsigned long baud;
            bool hw_ctrl;

            enum
            {
                NET_PARITY_NONE,
                NET_PARITY_ODD,
                NET_PARITY_EVEN
            } parity;
        } cfg;
    } serial;
};

union net_server
{
    struct net_server_common
    {
        enum net_domain domain;
        unsigned max_players;
        struct net_event ev;
    } common;

    struct net_server_ipv4
    {
        struct net_server_common common;
        short port;
    } ipv4;

    struct net_server_serial
    {
        struct net_server_common common;
        struct net_serial_cfg cfg;
    } serial;
};

struct net_host;

int net_init(void);
void net_deinit(void);
int net_update(struct net_host *s);
bool net_available(enum net_domain d);
struct net_host *net_server(const union net_server *srv);
struct net_host *net_connect(const union net_connect *c);
int net_write(struct net_host *h, net_peer p, const void *buf, size_t n);
int net_set_event(struct net_host *h, const struct net_event *ev);
int net_close(struct net_host *s);
enum net_role net_role(const struct net_host *s);
const char *net_domain_str(enum net_domain d);

#ifdef __cplusplus
}
#endif

#endif /* NET_H */
