#include "UDPSocket.h"
#include <string>
#include <algorithm>

UDPSocket::UDPSocket()
{
}

int UDPSocket::init(void)
{
    return 0;
}

// Server initialization
int UDPSocket::bind(int port)
{
    if (ip->bind(port)) {
        return 0;
    } else {
        return -1;
    }
}

// -1 if unsuccessful, else number of bytes written
int UDPSocket::sendTo(Endpoint &remote, char *packet, int length)
{
    if (!ip->open(remote.get_address(), remote.get_port(), IPStack::UDP)) {
        return -1;
    }

    if (_blocking) {
        return ip->write(packet, length, -1);
    } else {
        return ip->write(packet, length, _timeout);
    }
}

// -1 if unsuccessful, else number of bytes received
int UDPSocket::receiveFrom(Endpoint &remote, char *buffer, int length)
{
    if (!ip->open(remote.get_address(), remote.get_port(), IPStack::UDP)) {
        return -1;
    }

    if (_blocking) {
        return ip->read(buffer, length, -1);
    } else {
        return ip->read(buffer, length, _timeout);
    }
}