#include "coregrade.h"
#include "clog.h"
#include "cfg.h"
#include "exceptions.h"
#include "input.h"
#include "coregrade_api.h"
#include "pgsql.h"

#include "coregrade_api_main.h"

#include <iostream>
#include <libpq-fe.h>

CoreGrade::CoreGrade() {
    // Open config
    this->pFile = fopen(COREGRADE_LOG, "a");
    Output2FILE::Stream() = pFile; 
    FILE_LOG(logINFO) << "COREGRADE is starting...";

    CfgReadConfig();
    logfmt(logINFO, "Version from config: %s", CfgReadChar("version"));
    
    // Open database
    FILE_LOG(logDEBUG) << "Connecting to database...";
    FILE_LOG(logDEBUG) << "host=" << CfgReadChar("database.host") << ", name=" << CfgReadChar("database.name") << ", user=" << CfgReadChar("database.user") << ", pass=***hidden***, port=" << CfgReadLong("database.port");

    this->db = 0;
    try {
        this->db = pgsql_db_connect(CfgReadChar("database.host"),
				CfgReadChar("database.name"), 
				CfgReadChar("database.user"),
				CfgReadChar("database.pass"),
				CfgReadLong("database.port") );
    } catch (...) {
        logfmt(logDEBUG, "Exception!");
    }
    logfmt(logDEBUG, "Database connection %s", this->db>0?"successful":"failed");
}

long CoreGrade::coregrade_api(CVars in, CVars &out) {
    long retval = PHP_API_BAD_PARAM;
    try {
	retval = coregrade_api_main(in, out);
    } catch (bad_parameter) {
	out["status"] = "Incorrect input parameter";
    } catch (...) { 
	out["status"] = "Unhandled exception";
    }
    return retval;
}

const char* CoreGrade::cfgReadChar(const char *parameter) {
    return CfgReadChar(parameter);
}

long CoreGrade::cfgReadLong(const char *parameter) {
    return CfgReadLong(parameter);
}

void CoreGrade::logMessage(const char *message) {
    FILE_LOG(logINFO) << message;
}

CoreGrade::~CoreGrade() {
    FILE_LOG(logINFO) << "COREGRADE is stopping...";
    if (db>0) {
	FILE_LOG(logDEBUG) << "Closing database connection";
	pgsql_close();
    }
    // Do we need it?
    if (this->pFile) {
	fclose(this->pFile);
    }
}

