module ViewQuery
  require 'uri'
  include URI;
  include Common;
  
  def querystring(document)
    startkey=ENV['PAGE_STARTKEY'];
    startkey_docid=ENV['PAGE_STARTKEY_DOCID'];
    map={};
    pairs=[];
    encode = { 'key' => true, 'keys' => true, 'startkey' => true, 'endkey' => true };
    limit="limit";
    document.each_pair do |k,v|
      v=v.to_s;
      if k == limit
        v=v.to_i + 1;
      end
      if encode[k]
        v=compact(v);
      end
      map[k]=v;
    end
    # pagination keys should already be JSON encoded
    if startkey
      map['startkey']=startkey;
    end
    if startkey_docid
      map['startkey_docid']=startkey_docid;
    end
    map.each_pair do |k,v|
      pairs.push( k.to_s + "=" + URI.escape(v.to_s) );
    end
    return pairs.join("&");
  end
end
