// ****************************************************************************
// Method: SocketConnection::Flush
//
// Purpose: 
//   Writes the entire contents of the connection's buffer onto the
//   socket file descriptor in chunks. It then clears the buffer.
//
//
// Programmer: Brad Whitlock
// Creation:   Tue Aug 29 12:17:37 PDT 2000
//
// Modifications:
//   Brad Whitlock, Tue Mar 26 13:29:20 PST 2002
//   Made it use socket functions so it is more portable.
//
//   Brad Whitlock, Thu Jan 25 18:42:50 PST 2007
//   I made it use MSG_NOSIGNAL so we don't get a signal in the event that
//   we can't write to the socket.
//
//   Eric Brugger, Tue Mar 13 09:18:48 PDT 2007
//   I made the use of MSG_NOSIGNAL conditional on its definition.
//
// ****************************************************************************
void
SocketConnection::Flush(AttributeSubject *subject)
{
    if(destFormat.Format == TypeRepresentation::BINARYFORMAT)
        Connection::Flush(subject);
    else
    {
//        std::cout << subject->TypeName() << " "
//                  << subject->CalculateMessageSize(*this)
//                  << std::endl;

        if(subject->GetSendMetaInformation())
        {
            MapNode meta;
            JSONNode node;

            subject->WriteMeta(meta);

            node["id"] = subject->GetGuido();
            node["typename"] = subject->TypeName();
            node["api"] = meta.ToJSONNode(false,false);

            const std::string& output = node.ToString().c_str();

#if defined(_WIN32)
            send(descriptor, (const char FAR *)output.c_str(), output.size(), 0);
#else
#ifdef MSG_NOSIGNAL
            send(descriptor, (const void *)output.c_str(), output.size(), MSG_NOSIGNAL);
#else
            send(descriptor, (const void *)output.c_str(), output.size(), 0);
#endif
#endif
        }

        MapNode child;
        JSONNode node;

        subject->Write(child);

        node["id"] = subject->GetGuido();
        node["typename"] = subject->TypeName();
        node["contents"] = child.ToJSONNode(false);

        const std::string& output = node.ToString();

#if defined(_WIN32)
            send(descriptor, (const char FAR *)output.c_str(), output.size(), 0);
#else
#ifdef MSG_NOSIGNAL
            send(descriptor, (const void *)output.c_str(), output.size(), MSG_NOSIGNAL);
#else
            send(descriptor, (const void *)output.c_str(), output.size(), 0);
#endif
#endif
        buffer.clear();
    }
}