#include "db_if.h"
#include "ConfigFile.h"
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <stdint.h>
#include <ctime>

DbIf::DbIf(int argc, char ** argv) {
	if(argc != 2) {
		fprintf(stderr, "Give a configuration file as the first argument to this program.\n");
		abort();
	}

	std::string db_file;
	try {
		ConfigFile conf(argv[1]);
		saltStore = new SaltStore(
			conf.read<uint64_t>("key_lifetime", 120),
			conf.read<size_t>("salt_size", 256),
			conf.read<std::string>("secret")
			);
		db_file = conf.read<std::string>("db_file");
	} catch(ConfigFile::file_not_found & e) {
		fprintf(stderr, "Could not open configuration file '%s'!\n", e.filename.c_str());
		abort();
	} catch(ConfigFile::key_not_found & e) {
		fprintf(stderr, "Could not find required configuration key '%s'!\n", e.key.c_str());
		abort();
	}

	db = new PosDb(db_file.c_str());
}

DbIf::~DbIf() {
	delete db;
	delete saltStore;
}

std::string DbIf::getSalt() {
	return saltStore->getSalt();
}

bool DbIf::consumeKey(std::string key) {
	return saltStore->consumeKey(key);
}

PosDb & DbIf::getDb() {
	return *db;
}
