<%!-lmysqlclient%><%#
#include <mysql/mysql.h>
#include <json/json.h>
#include "connectioninfo.H"
using namespace CP;
using namespace cppsp;

MYSQL* db=NULL;
int rn;
int r;
long unsigned int len1;
MYSQL_STMT* stmt;
MYSQL_BIND param[1], results[1];
%>
{ "json": [ <%
int queries=1;
auto it=request->queryString.find("queries");
if(it!=request->queryString.end()) {
	queries=atoi((*it).second);
}
if(queries<1)queries=1;
if(queries>500)queries=500;
int i;
char query[256];

if(db==NULL) {
	db=doConnect(NULL);
	stmt=mysql_stmt_init(db);
	const char* sql="SELECT randomNumber FROM World WHERE id = ?";
	mysql_stmt_prepare(stmt,sql,strlen(sql));
	memset(param, 0, sizeof(param));
	memset(results, 0, sizeof(results));
	param[0].buffer_type = MYSQL_TYPE_LONG;
	param[0].buffer = (char *)&rn;
	param[0].buffer_length = sizeof(rn);
	param[0].is_null = 0;
	param[0].length = NULL;
	results[0].buffer_type= MYSQL_TYPE_LONG;
	results[0].buffer = &r;
	results[0].buffer_length = sizeof(r);
	results[0].is_null = 0;
	results[0].length = &len1;
	if(mysql_stmt_bind_param(stmt,param)) throw runtime_error(mysql_stmt_error(stmt));
	if(mysql_stmt_bind_result(stmt, results)) throw runtime_error(mysql_stmt_error(stmt));
}
int items[queries];
for (int i=0;i<queries;i++){
	rn=rand()%10000;
	if(mysql_stmt_execute(stmt)) throw runtime_error(mysql_stmt_error(stmt));
	if(mysql_stmt_fetch(stmt)==0) {
		items[i]=r;
	} else {
		items[i]=0;
	}
}
for (int i=0;i<queries;i++){
	if(i>0) {%>, <%}
	%>{ "randomNumber": <%=items[i]%> }<%
}

response->headers["Content-Type"]="application/json";
response->headers["Server"]="cppsp/0.2";
%> ] }
