/*!
  \file
  \brief Lua への network モジュール登録

  \author Satofumi KAMIMURA

  $Id: luabindNetwork.cpp 1960 2011-08-02 14:12:32Z satofumi $
*/

#include "luabindNetwork.h"
#include "TcpipSocket.h"
#include "ConnectionUtils.h"
#include <luabind/luabind.hpp>
#include <algorithm>
#include <string>

using namespace qrk;
using namespace luabind;
using namespace std;


namespace
{
    enum {
        BufferSize = 1024,
    };


    string connection_receive(Connection* connection, size_t size, int timeout)
    {
        char buffer[BufferSize];

        size_t actual_size = min(size, static_cast<size_t>(BufferSize - 1));
        int n = connection->receive(buffer, actual_size, timeout);

        if (n <= 0) {
            return "";
        }

        buffer[n] = '\0';
        return buffer;
    }


    string connection_readline(Connection* connection, int timeout)
    {
        char buffer[BufferSize];

        int n = readline(connection, buffer, BufferSize - 1, timeout);
        if (n <= 0) {
            return "";
        }

        return buffer;
    }
}


void qrk::luabindNetwork(lua_State* L)
{
    module(L)
        [
         class_<Connection>("Connection"),

         class_<TcpipSocket, Connection>("TcpipSocket")
         .def(constructor<>())
         .def(constructor<void*>())
         .def("what", &TcpipSocket::what)
         .def("connect", &TcpipSocket::connect)
         .def("disconnect", &TcpipSocket::disconnect)
         .def("isConnected", &TcpipSocket::isConnected)
         .def("send", &TcpipSocket::send)
         .def("size", &TcpipSocket::size)
         .def("flush", &TcpipSocket::flush)
         .def("clear", &TcpipSocket::clear)
         .def("ungetc", &TcpipSocket::ungetc),

         def("connection_readline", &connection_readline),
         def("connection_receive", &connection_receive)
         ];
}
