#include <stdio.h>
#include <string.h>
#include <sqlite3.h>
#include "dbase.h"

#define WORKSECONDS 28800

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


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

int DBase_ResolveUserID(int offset){
	int ret=0;
	sprintf(SQLQuery,"SELECT Person_id FROM lide WHERE Person_id < 1000 LIMIT 1 OFFSET %u",offset);
	rc = sqlite3_prepare_v2(db,SQLQuery,sizeof(SQLQuery),&stmt,0);
	if(rc)
		return(-1);
	rc = sqlite3_step(stmt);

	if(rc == SQLITE_ROW)
		ret = sqlite3_column_int(stmt,0);
	sqlite3_finalize(stmt);
	return ret; 
}

unsigned char* DBase_GetAttendRow(void){
	rc = sqlite3_step(stmt);

	if(rc == SQLITE_ROW)
		 return((unsigned char*) sqlite3_column_text(stmt,0));
	else
	sqlite3_finalize(stmt);
	return NULL; 


}
char DBase_TodayIsFreeday(void){
	strcpy(SQLQuery,"SELECT * FROM 'svatky' WHERE Datum = strftime('%d.%m','now')");
	sqlite3_prepare_v2(db,SQLQuery,sizeof(SQLQuery),&stmt,0);
	rc = sqlite3_step(stmt);
	if(rc == SQLITE_ROW){
		freeday=1;		
		return(1);
	}
	else{ 
		freeday=0;
		return(0);
	}
}

int DBase_SetUserID(int id){
	int rc=0;
	sprintf(SQLQuery,"SELECT Location || Date_time FROM daily.dochazka WHERE Person_id = %u ORDER BY Date_time DESC",id);
	rc = sqlite3_prepare_v2(db,SQLQuery,sizeof(SQLQuery),&stmt,0);
	return(rc);

}

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


}
int DBase_InsertStats(int dayofweek, int day, int userId, int work, int lunch, int other){
	int saldo;
	if((dayofweek==0)||(dayofweek==6)||(freeday)) saldo = work;
	else saldo = work - WORKSECONDS;
	sprintf(SQLQuery,"UPDATE evidence SET Saldo = Saldo+(%d), '%u'='%u:%02u;%u:%02u;%u:%02u' WHERE Person_id = %u",saldo,day,work/3600,(work%3600)/60,lunch/3600,(lunch%3600)/60,other/3600,(other%3600)/60,userId);
	return(sqlite3_exec(db,SQLQuery,0,0,0));


}


