 misc     = require('./misc')
 defaults = misc.defaults
 required = defaults.required
+_        = require('underscore')
 
 
 message = (obj) ->

Queries directly to the database (sort of like Facebook's GraphQL)
###

API message
    event          : 'query'
    id             : undefined
    query          : required
    changes        : undefined
    multi_response : false
    options        : undefined

message
    event : 'query_cancel'

        defaults(opts, obj)
    return obj

# message2 for "version 2" of the message definitions
# TODO document it, for now just search for "message2" to see examples
message2 = (obj) ->

    mk_descr = (val) ->
        descr = val.descr 
        descr += ' (required)' if val.init == required
        return descr

    init   = _.mapObject(obj.fields, ((val) -> val.init))
    fdescr = _.mapObject(obj.fields, mk_descr)
    exports.documentation[obj.event] =
                                descr : obj.descr ? ''
                                fields: fdescr
    exports.tests[obj.event] = obj.tests

    exports[obj.event] = (opts={}) ->
        if opts.event?
            throw Error("ValueError: must not define 'event' when calling message creation function (opts=#{JSON.stringify(opts)}, obj=#{JSON.stringify(obj)})")
        defaults(opts, init)
    return obj

# messages that can be used by the HTTP api.   {'event':true, ...}
exports.api_messages = {}

# this holds the documentation for the message protocol
exports.documentation = {}

# holds all the tests
exports.tests = {}

API = (obj) ->
    exports.api_messages[obj.event] = true
