/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>

#include "userinfo.h"

PUserInfo::PUserInfo()
{
	Name="";
	Surname="";
    	ID=0;
	PIN=1234;
	RFID="";
	Rights=' ';
	Group=0;
	this->dbReconnect();
}

PUserInfo::~PUserInfo(){
	QString connection;
	connection=db->connectionName();
	db->close();
	delete db;
	QSqlDatabase::removeDatabase(connection);


}

void PUserInfo::dbReconnect(void){

db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE"));
db->setDatabaseName("/sdcard/test.db");

}

QStringList* PUserInfo::CheckNoFprUsers(void){

users = new QStringList;

db->open();

QSqlQuery query(QString("select Person_ID,Jmeno,Prijmeni FROM lide where Otisk = ' '"));
	while(query.next()){
		users->append(query.value(0).toString() + " " + query.value(1).toString() + " " + query.value(2).toString());	
	}
	db->close();
	return users;

}

void PUserInfo::SetNameSurname(const QString &t_name,const QString &t_surname){
	Name=t_name;
	Surname = t_surname;
}

int PUserInfo::UserExist(){

	db->open();

	QSqlQuery query(QString("select Person_id from lide where Jmeno = '%1' AND Prijmeni = '%2'").arg(Name).arg(Surname));
	int t_ID=0;
	query.last();	  
	  if (!(query.at()))
		    {
		    t_ID = query.value(0).toInt();
			}
	
		db->close();
		return t_ID;
}

int PUserInfo::ObtainUserID(){

	int t_ID;	
		
	db->open();
	QSqlQuery query(QString("select Person_id from lide WHERE Person_id > 1000 LIMIT 1"));
	query.last();	
	if (!(query.at())){
		InsertType = ActReplace;
		t_ID=(query.value(0).toInt())-1000;		
    }
	else{
		query.exec(QString("select Person_id from lide WHERE Person_id < 1000 ORDER BY Person_id DESC LIMIT 1"));
		query.next();
		InsertType = ActInsert;
		t_ID=(query.value(0).toInt())+1;
    }

db->close();
ID=t_ID;	
return t_ID;
}

bool PUserInfo::UserFprUpdate(void){

InsertType=ActUpdate;

return(UserStore());


}

bool PUserInfo::UserDelete(){
//Atomic operation
if(!RemoveFprFromReader(ID))
	return(NULL);

db->open();

if(db->isOpen()){
	int ret;
 QSqlQuery query;
	ret = query.exec(QString("UPDATE lide SET 'Person_ID'=%1,'Jmeno'=' ','Prijmeni'=' ','Otisk'='-','RFID'=' ','Opravneni'=' ', 'Skupina'=0 ,'PIN'=0 WHERE Person_ID = %2").arg(ID+1000).arg(ID));
	db->close();
	return(ret);
	}
else return(NULL);


}

bool PUserInfo::UserStore(){
	bool ret=0;	


QString Fingerprint;
if(InsertType!=ActDataUpdate){
QFile file("/var/tmp/template");
if (!file.open(QIODevice::ReadOnly))
return 1;

Fingerprint=file.readAll().toHex();

file.remove();
}



	db->open();
	if (db->isOpen()){
   		QSqlQuery query;


		if(InsertType==ActReplace)
    			ret = query.exec(QString("UPDATE lide SET 'Person_ID'=%1,'Jmeno'='%2','Prijmeni'='%3','Otisk'='%4','RFID'='%5','Opravneni'='%6','Skupina' = %7, 'PIN'=%8, 'OtiskUpdate' = date('now') WHERE Person_ID = %9").arg(ID).arg(Name).arg(Surname).arg(Fingerprint).arg(QString(RFID)).arg(Rights).arg(Group).arg(PIN).arg(ID+1000));
		else if(InsertType==ActInsert)
			ret = query.exec(QString("INSERT INTO lide ('Person_ID','Jmeno','Prijmeni','Otisk','RFID','Opravneni','Skupina','PIN','OtiskUpdate') VALUES (%1,'%2','%3','%4','%5','%6','%7',%8,date('now'))").arg(ID).arg(Name).arg(Surname).arg(Fingerprint).arg(QString(RFID)).arg(Rights).arg(Group).arg(PIN));
		else if(InsertType==ActUpdate)
			ret = query.exec(QString("UPDATE lide SET 'Otisk'='%1','OtiskUpdate' = date('now') WHERE Person_ID = %2").arg(Fingerprint).arg(ID));
		else if(InsertType==ActDataUpdate)
			ret = query.exec(QString("UPDATE lide SET 'Jmeno'='%1','Prijmeni'='%2','RFID'='%3','Opravneni'='%4','Skupina'='%5','PIN'=%6 WHERE Person_ID = %7").arg(Name).arg(Surname).arg(QString(RFID)).arg(Rights).arg(Group).arg(PIN).arg(ID));
		db->close();		
		return(ret);
	}
	else return 0;

}

QString PUserInfo::GetName() const{

return Name;
}

QString PUserInfo::GetSurname() const{

return Surname;
}

int PUserInfo::GetGroup() const{

return Group;
}

QChar PUserInfo::GetRights() const{

return Rights;
}

QString PUserInfo::GetFprDate() const{

return FprDate;
}

QString PUserInfo::GetRFID() const{

return RFID;

}

int PUserInfo::GetID() const{

return ID;
}

void PUserInfo::SetUserID(int id){

ID = id; 

}

void PUserInfo::SetRFID(QByteArray rfid){

RFID = rfid; 

}

void PUserInfo::SetPIN(int pin){

PIN = pin; 

}

void PUserInfo::SetRights(QChar rights){

Rights = rights;

}


void PUserInfo::SetGroup(int group){

Group = group;

}

bool PUserInfo::DownloadFprToReader(){

		QFile file("/var/pipes/prstd_in");	
		char userstore[5];

		if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
 			return 0;
		sprintf(userstore,"X%u\n",this->ID);
		file.write(userstore);	
		file.close();
		return 1;

}

bool PUserInfo::RemoveFprFromReader(int fpr_id){

QFile file("/var/pipes/prstd_in");	
		char userstore[5];

		if (!file.open(QIODevice::WriteOnly))
 			return 0;
		sprintf(userstore,"D%u\n",fpr_id);
		file.write(userstore);	
		file.close();
		return 1;

}

QSqlQueryModel* PUserInfo::GetUserList(PRights * rights ,QString filter) {

	db->open();

	if(db->isOpen()){
 	QSqlQueryModel *model = new QSqlQueryModel;
	if(rights->GetRights()==PRights::SuperAdmin) 
	model->setQuery(QString("SELECT Person_id, Jmeno, Prijmeni FROM lide WHERE Prijmeni LIKE '%1\%' AND Person_id < 1000").arg(filter));
	else
	model->setQuery(QString("SELECT Person_id, Jmeno, Prijmeni FROM lide WHERE Prijmeni LIKE '%1\%' AND (Opravneni='G' OR Opravneni='U') AND Skupina = %2 AND Person_id < 1000").arg(filter).arg(rights->GetGroup()));
   
	return(model);
	db->close();
	}
	else return(NULL);
}

bool PUserInfo::ObtainUserData(){

	if(!ID) 
		return false;
	db->open();
	if(db->isOpen()){
		QSqlQuery query(QString("SELECT Jmeno, Prijmeni, Opravneni, Skupina, RFID, PIN, OtiskUpdate FROM lide WHERE Person_id = %1").arg(ID));  
		query.last();	  
	  if (!(query.at()))
		    {
		    Name = query.value(0).toString();
			Surname = query.value(1).toString();
			Rights = query.value(2).toString()[0]; //Ymenit
			Group = query.value(3).toInt();
			RFID = query.value(4).toByteArray();
			PIN = query.value(5).toInt();		
			FprDate = query.value(6).toString();	
			}
	
		db->close();
		return true;
	}
	return false;
}

QStringList* PUserInfo::GetGroupList(void){

QStringList *groups = new QStringList;

	db->open();
	if(db->isOpen()){
		QSqlQuery query(QString("SELECT Nazev FROM Skupiny"));
			while(query.next()){
				groups->append(query.value(0).toString());	
			}
			db->close();
			return groups;
	}
	return NULL;
}

bool PUserInfo::UserDataUpdate(void){

	InsertType = ActDataUpdate;
	return(UserStore());
	

}
