module Ubiquity
  module Mongo
    module Driver
      module Protocol
        class Message

          include Ubiquity::Mongo::Driver::Protocol::Serializers


          class << self

            ##
            #
            ##
            def next_request_id
              @next_request_id ||= 0

              if @next_request_id + 1 > 2147483647
                @next_request_id = 1
              else
                @next_request_id += 1
              end


              @next_request_id
            end

          end # class << self

          attr_accessor :opts, :request_id

          ##
          #
          ##
          def initialize(connection, database_name, collection_name, opts = {})
            @connection      = connection
            @database_name   = database_name
            @collection_name = collection_name
            @opts            = opts
            @request_id      = self.class.superclass.next_request_id
          end

          ##
          # execute this command
          ##
          def execute
            @connection.send_data(command)
          end

          ##
          # Return the fully qualified name to the collection
          ##
          def fqn
            "#{@database_name}.#{@collection_name}"
          end

          ##
          # Produce a command by concatinating the header and the body
          ##
          def command
            reset_message_ptr
            buffer = body
            len = HEADER_SIZE + message_ptr
            header = serialize_header([len, @request_id, 0, op_code])
            header + buffer
          end


        end
      end
    end
  end
end
