#include "mobideliv.h"
#include "clog.h"
#include "cfg.h"
#include "exceptions.h"
#include "input.h"
#include "mobideliv_api.h"
#include "pgsql.h"

#include "mobideliv_api_main.h"

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

MobiDeliv::MobiDeliv() {
    // Open config
    this->pFile = fopen(MOBIDELIV_LOG, "a");
    Output2FILE::Stream() = pFile; 
    FILE_LOG(logINFO) << "MOBIDELIV 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 MobiDeliv::mobideliv_api(CVars in, CVars &out) {
    long retval = PHP_API_BAD_PARAM;
    try {
	retval = mobideliv_api_main(in, out);
    } catch (bad_parameter) {
	out["status"] = "Incorrect input parameter";
    } catch (...) { 
	out["status"] = "Unhandled exception";
    }
    return retval;
}

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

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

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

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

