
#include <sqlite3.h>
#include "common.h"


char SQLQuery[100];
sqlite3 *db;
char *zErrMsg = 0;
sqlite3_stmt *stmt;
void* DBCallback = NULL;
int rc;

void DBase_CallbackRegister(void* callback){

DBCallback = callback;

}


int DBase_Open(char * path){
rc = sqlite3_open(path, &db);
    if( rc ){
      sqlite3_close(db);
      return(sqlite3_errcode(db));
	}
	else
	return(0);
}

int DBase_Query(char * query,int actioncode){
 rc = sqlite3_exec(db, query, DBCallback, (void*) actioncode, &zErrMsg);
    if( rc!=SQLITE_OK ){
      syslog(LOG_MAKEPRI(LOG_LOCAL1, LOG_ERR),"DBASE Query failed ! %s", zErrMsg);
      sqlite3_free(zErrMsg);
	  return(rc);    
	}
	return(0);
}

int DBase_UserNameResolve(int userID){
	sprintf(SQLQuery,"SELECT Opravneni || Skupina,Jmeno,Prijmeni FROM lide WHERE Person_id = %u",userID);
	return(DBase_Query(SQLQuery,DBASE_NAMERESOLVE_CODE));
}

int DBase_AttachDaily(char *path){
	sprintf(SQLQuery,"ATTACH DATABASE '%s' AS daily",path);
	return(DBase_Query(SQLQuery,DBASE_NO_OUTPUT_CODE));


}

int DBase_LogEntry(int userID,char terminal,char modif){
	if(modif)
	sprintf(SQLQuery,"INSERT INTO daily.dochazka VALUES (%u,\"%c%c\",datetime('now','localtime'))",userID,terminal,modif);
	else
	sprintf(SQLQuery,"INSERT INTO daily.dochazka VALUES (%u,\"%c\",datetime('now','localtime'))",userID,terminal);

	return(DBase_Query(SQLQuery,DBASE_NO_OUTPUT_CODE));
}

int DBase_EntryTypeResolve(int userID){
	
	char* ret;
	sprintf(SQLQuery,"SELECT Location FROM daily.dochazka WHERE Person_id = %u ORDER BY Date_time DESC LIMIT 1",userID);
	rc = sqlite3_prepare_v2(db,SQLQuery,sizeof(SQLQuery),&stmt,0);
	if(rc)
		return(-1);
	rc = sqlite3_step(stmt);

	if(rc == SQLITE_ROW){
		ret = (char*) sqlite3_column_text(stmt,0);
		if(ret[1]!='*')
			rc=1; //Příchod
		else 
			rc=0;	//Odchod
	}
	else rc = 1;
	sqlite3_finalize(stmt);
	return rc; 
}

int DBase_GetFprTemplate(int userID){
	sprintf(SQLQuery,"SELECT Person_id,Otisk FROM lide WHERE Person_id = %u",userID);
	return(DBase_Query(SQLQuery,DBASE_GETFPRTEMPATE_CODE));
}


   
