module Connectors
  module Helpers
    module InsertCommand

      # when included, this module adds method #insert and alias for it.
      # Alias name depends on base class name.
      # We need this alias to forward methods from MongoConnector to resources connectors.

      def self.included(base)
        resource_name = base.to_s.underscore_class
        method_name = "#{resource_name}_insert".to_sym
        alias_method method_name, :insert
      end

      def insert(record)
        begin
          record.validate!
          hash = record.to_mongo_hash
          hash["created_at"] = Time.now.to_i
          collection.insert(hash)
          record
        rescue Mongo::OperationFailure => e
          # exception's message doesn't always start from error code
          if e.message =~ /11000/
            resource_name = record.class.to_s.underscore_class
            raise InvalidRecord.new("Duplicate key error: #{resource_name} with id '#{record.id}'")
          end
        end
      end

    end
  end
end
