#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "db.h"
#include "util.h"

#define DB_CACHE_BYTES (256u * 1024)

static PGconn *pg;
static redisContext *rc;
static int recycle_pg;

PGconn *
db_get(const struct conf *cf)
{
	if (pg != NULL && PQstatus(pg) == CONNECTION_OK)
		return pg;
	if (pg != NULL)
		PQfinish(pg);
	recycle_pg = 0;
	pg = PQconnectdb(conf_get(cf, "db.conninfo", "dbname=signet"));
	if (PQstatus(pg) != CONNECTION_OK) {
		log_err("database connection failed");
		PQfinish(pg);
		pg = NULL;
	}
	return pg;
}

/* libpq retains large I/O buffers even after PQclear(). Do not carry them
 * across API requests; never close an in-flight query or worker transaction. */
void
db_request_done(void)
{
	if (recycle_pg && pg != NULL) {
		PQfinish(pg);
		pg = NULL;
	}
	recycle_pg = 0;
}

redisContext *
redis_get(const struct conf *cf)
{
	redisReply *r;

	if (rc != NULL && !rc->err) {
		if ((r = redisCommand(rc, "PING")) != NULL) {
			freeReplyObject(r);
			return rc;
		}
	}
	redis_drop();
	rc = redisConnect(conf_get(cf, "redis.host", "127.0.0.1"),
	    atoi(conf_get(cf, "redis.port", "6379")));
	if (rc == NULL || rc->err) {
		log_err("Redis connection unavailable");
		redis_drop();
	}
	return rc;
}

void
redis_drop(void)
{
	if (rc != NULL)
		redisFree(rc);
	rc = NULL;
}

PGresult *
db_q(PGconn *c, const char *sql, int n, const char *const *params)
{
	PGresult *res;
	ExecStatusType st;
	size_t bytes = 0, len;
	int i;

	if (c == pg) {
		for (i = 0; i < n; i++) {
			if (params[i] == NULL)
				continue;
			len = strlen(params[i]);
			if (len >= DB_CACHE_BYTES - bytes) {
				recycle_pg = 1;
				break;
			}
			bytes += len;
		}
	}
	res = PQexecParams(c, sql, n, NULL, params, NULL, NULL, 0);
	st = PQresultStatus(res);
	if (c == pg && res != NULL && PQresultMemorySize(res) >= DB_CACHE_BYTES)
		recycle_pg = 1;
	if (st != PGRES_TUPLES_OK && st != PGRES_COMMAND_OK) {
		/* DETAIL/CONTEXT and server messages can repeat private parameters. */
		log_err("database query failed (SQLSTATE %.5s)",
		    res != NULL && PQresultErrorField(res, PG_DIAG_SQLSTATE) != NULL ?
		    PQresultErrorField(res, PG_DIAG_SQLSTATE) : "?????");
		PQclear(res);
		return NULL;
	}
	return res;
}

int
db_do(PGconn *c, const char *sql, int n, const char *const *params)
{
	PGresult *res = db_q(c, sql, n, params);

	if (res == NULL)
		return -1;
	PQclear(res);
	return 0;
}
