#include <QtGui>
#include <QIcon>
#include <QCommonStyle>

#include "addwizard.h"
// Hokusssssák
/*
addwizard::addwizard(Action CurrentAction){
	
	if(CurrentAction == UpdateFprOnly){



	}
}
*/

//! [0] //! [1]
addwizard::addwizard(QWidget *parent,PRights* rights, Action curract,int ID) 
{

    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    setAttribute(Qt::WA_DeleteOnClose);
	
	UserRights = rights;
	CurrentAction=curract;	

	CurrentUser = new PUserInfo;

	//Create bottom navigation bar	
	QCommonStyle style;
	
	Next = new QPushButton("&Další", this);
	Next->setIcon(style.standardIcon(QStyle::SP_ArrowForward));
	Next->setLayoutDirection(Qt::RightToLeft);
	
	Prev = new QPushButton("&Předchozí", this);
	Prev->setIcon(style.standardIcon(QStyle::SP_ArrowBack));
	
	Cancel = new QPushButton("&Zrušit", this);
	Cancel->setIcon(style.standardIcon(QStyle::SP_DialogCancelButton));
	Prev->setVisible(false);
	SetColor();
	QHBoxLayout* buttonLayout = new QHBoxLayout;
    


    buttonLayout->addWidget(Cancel);
	buttonLayout->addStretch();    
	buttonLayout->addWidget(Prev);
    buttonLayout->addWidget(Next);
	buttonLayout->setContentsMargins(11,11,11,11);
	connect(Next, SIGNAL(clicked()), this, SLOT(buttNext()));
	connect(Prev, SIGNAL(clicked()), this, SLOT(buttPrev()));
	connect(Cancel, SIGNAL(clicked()), this, SLOT(buttCanc()));
	//cdconnect(this,SIGNAL(destroyed()),this,SLOT(buttCanc()));
	
	//Create wizard header
	

	if(ID!=0){
	CurrentAction=UpdateFprOnly;
	CurrentUser->SetUserID(ID);
	}
	else{
		

	
	QStringList items=*(CurrentUser->CheckNoFprUsers());
	if(items.size()){
	
	
	bool ok=false;
	QString item = QInputDialog::getItem(this,"Upozornění",
                                          "V databázi jsou uživatelé (" + QString::number(items.size()) + ")\nbez platného otisku.\n\nAktualizovat otisk uživateli:", items, 0, false, &ok);


	if(ok){
		ID = item.section(' ', 0, 0).toInt();
		CurrentUser->SetUserID(ID);
		QMessageBox::warning(this,"Hola!","Budeme ladit pána č."+ ID, QMessageBox::Ok);
		CurrentAction=UpdateFprOnly;
		Next->setIcon(style.standardIcon(QStyle::SP_DialogApplyButton));
		Next->setText("Aktualizovat");
	}
	
	}

	}	
    
	stackedlayout = new QStackedLayout;

	if(CurrentAction==AddUser){
	stackedlayout->addWidget(CreateGetNamePage());
	stackedlayout->addWidget(CreateScanFPRPage());
 	stackedlayout->addWidget(CreateOthersPage());
	stackedlayout->addWidget(CreateGroupPage());
 	}
	else {stackedlayout->addWidget(CreateScanFPRPage());
	Next->setText("&Aktualizovat");	
	Next->setIcon(style.standardIcon(QStyle::SP_DialogOkButton));
	}

	QVBoxLayout *mainLayout = new QVBoxLayout;
	if(CurrentAction == AddUser)
	mainLayout->addLayout(utility::CreateHeader(("    Průvodce přidáním uživatele"), "AddUser"));
	else
	mainLayout->addLayout(utility::CreateHeader(("    Aktualizace otisku - uživatel " + QString::number(ID)),"AddUser"));
	mainLayout->addLayout(stackedlayout, Qt::AlignCenter);
	mainLayout->addLayout(buttonLayout, Qt::AlignBottom);
	mainLayout->setContentsMargins(0,0,0,0);

	CurrentState = PageName;

    	setLayout(mainLayout);

	if(CurrentAction == AddUser){	
	NameEdit->setFocus();	
	utility::SetKeyboardMode(utility::KBMode_Alpha);
	}

	
	

//! [7]
}



void addwizard::keypressed(QByteArray &keyt){



if((keyt[0]=='#') && (CurrentAction==AddUser)){
QChar key = utility::WinToUtf(keyt[1]);
	if (NameEdit->hasFocus()){
		NameEdit->Keypressed(keyt);
	}
	else if(SurnameEdit->hasFocus()){
		SurnameEdit->Keypressed(keyt);
	}
	else if(PinEdit->hasFocus()){
	
		if((key=='#')){
		PinEdit->backspace();
		}		
		else{
		PinEdit->setText(PinEdit->text().replace(PinEdit->text().length(),1,key));		
		}
	}
	
}

else if(keyt[0]=='P'){
QString message;
	
	switch(keyt[1]){
	case '0' :	
	message = "Přiložte prst prosím";	
	break;	
	case '1' :
	message = "Scanuji 1. vzorek...";
	break;
	case '2' :
	message = "Sundejte prst z čtečky";
	break;
	case '3' :
	message = "Přiložte prst znovu prosím";
	break;
	case '4' :
	message = "Scanuji 2. vzorek...";
	break;
	case '5' :
	message = "Dokončeno,sundejte prst z čtečky";
	ScanFinger->setEnabled(true);
	Next->setEnabled(true);
	break;
	default :
	message = "";
	}

ScanStatus->setText(message);

}

}

void addwizard::buttCanc(void){

delete CurrentUser;
if(CurrentAction==AddUser)
utility::SetKeyboardMode(utility::KBMode_Leaving);
this->close();


}

void addwizard::buttScan(void){

	

 QFile file("/var/pipes/prstd_in");
 if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
 return;
Speaker = new QProcess();
Speaker->start("madplay -Q /sdcard/Hlaska.mp3 &");
 file.write("S\n");
 file.close();
ScanFinger->setEnabled(false);
Next->setEnabled(false);

}



void addwizard::buttNext(void){

int t_ID;
int ret; 
if(CurrentAction==UpdateFprOnly){
	if(CurrentUser->UserFprUpdate() && CurrentUser->DownloadFprToReader())QMessageBox::information(this,"Úspěch","Otisk aktualizován.", QMessageBox::Ok);
	else QMessageBox::critical(this,"Chyba","Při aktualizaci otisku se vyskytla chyba.", QMessageBox::Ok);
	
	buttCanc();
	return;


}

switch (CurrentState){
		case PageName :
		CurrentUser->SetNameSurname(NameEdit->text().trimmed(), SurnameEdit->text().trimmed());
		
		if((NameEdit->text().size()==0)||(SurnameEdit->text().size()==0)){
			QMessageBox::warning(this,"PRST",
                                "Nezadal jste potřebné údaje !",
                                QMessageBox::Ok
                                );
		return;
		}		
		t_ID = CurrentUser->UserExist();			
		if(t_ID){
			/*QMessageBox::warning(this,"PRST",
                                ,
                                QMessageBox::Ok
                                );
			*/
			utility::PixmapMessageBox("Existující uživatel","Uživatel " + NameEdit->text() + " " + Surname + " již existuje !\nJeho ID je " + QString::number(t_ID),QPixmap("/sdcard/UserWarning.png"),QMessageBox::Ok);
		return;
		}

		ret = utility::PixmapMessageBox("Přidat?","Skutečně chcete přidat uživatele\n" + NameEdit->text() + " " +  SurnameEdit->text() + " s ID = " + QString::number(CurrentUser->ObtainUserID()) + " ?",QPixmap("/sdcard/UserQuestion.png"), QMessageBox::Yes | QMessageBox::No);
		if(ret == QMessageBox::No) return;
		
		//Go to next screen
		Prev->setVisible(true);
		CurrentState = PageFingerprint;
		break;
		
		case PageFingerprint :	

		CurrentState = PageOther;	
		
		utility::SetKeyboardMode(utility::KBMode_Numeric);
	
		break;

		case PageOther :
		Next->setText("&Dokončit");
		CurrentState = PageGroup;	

		CurrentUser->SetPIN(PinEdit->text().toInt());
		break;

		case PageGroup :
		

		char rights=' ';

		if(SuperAdmin->isChecked())
		rights='A';
		else if(GroupAdmin->isChecked())
		rights='G';
		else if(StandardUser->isChecked())
		rights='U';

		CurrentUser->SetRights(rights);
		CurrentUser->SetGroup(GroupSelectBox->currentIndex());
		if(CurrentUser->UserStore() && CurrentUser->DownloadFprToReader()){ QMessageBox::information(this,"Úspěch","Uživatel úspěšně přidán.", QMessageBox::Ok);		
		buttCanc();
		}
		else QMessageBox::critical(this,"Chyba","Při vkládání uživatele se vyskytla chyba.", QMessageBox::Ok);
}

	stackedlayout->setCurrentIndex(CurrentState);	
 

}



void addwizard::buttPrev(void){
	switch (CurrentState){
		case PageFingerprint :
			Prev->setVisible(true);
			CurrentState = PageName;
		break;
		case PageOther :
			
		utility::SetKeyboardMode(utility::KBMode_Alpha);

		CurrentState = PageFingerprint;
		break;
		case PageGroup :			
		Next->setText("&Další");
		CurrentState = PageOther;
		
	}


stackedlayout->setCurrentIndex(CurrentState);	
}

QWidget* addwizard::CreateGetNamePage(void){

NameEdit = new PLineEdit();
SurnameEdit = new PLineEdit();
QWidget* PageWidget = new QWidget(this);
QFormLayout* formLayout = new QFormLayout;
	formLayout->addRow("&Jméno:", NameEdit);
 	formLayout->addRow("&Příjmení:", SurnameEdit);
	formLayout->setFormAlignment(Qt::AlignCenter);
PageWidget->setLayout(formLayout);

return PageWidget;

}

QWidget* addwizard::CreateScanFPRPage(void){

	QWidget* PageWidget = new QWidget(this);
	QVBoxLayout* Layout2 = new QVBoxLayout(this);

		ScanFinger =  new QPushButton("&Spustit skenování", this);
		ScanStatus = new QLabel("Skenování prstíčku");
		ScanStatus->setAlignment(Qt::AlignCenter);
	
		Layout2->addWidget(ScanStatus,Qt::AlignCenter);
		Layout2->addWidget(ScanFinger,Qt::AlignCenter);
		connect(ScanFinger, SIGNAL(clicked()), this, SLOT(buttScan()));
		PageWidget->setLayout(Layout2);

	return PageWidget;
}

QWidget* addwizard::CreateOthersPage(void){

QWidget* PageWidget = new QWidget(this);

QHBoxLayout* Layout3 = new QHBoxLayout(this);	

	QGroupBox *groupBox1 = new QGroupBox(tr("RFID Karta"));
    groupBox1->setCheckable(true);
    groupBox1->setChecked(false);
	connect(groupBox1, SIGNAL(toggled(bool)), this, SLOT(RfidToggled(bool)));
	QVBoxLayout *vbox1 = new QVBoxLayout;

	RfidEdit = new PLineEdit;
	LoadRfid = new QPushButton("&Načti kartu");
	vbox1->addWidget(RfidEdit);
	vbox1->addWidget(LoadRfid);
 	groupBox1->setLayout(vbox1);

//****************************************
	QGroupBox *groupBox2 = new QGroupBox(tr("PIN"));
    groupBox2->setCheckable(true);
    groupBox2->setChecked(false);
	connect(groupBox2, SIGNAL(toggled(bool)), this, SLOT(PinToggled(bool)));

	PinEdit = new QLineEdit();
	//PinEdit->setEchoMode(QLineEdit::Password);
	PinEdit->setMaxLength(4);
	
	QVBoxLayout *vbox2 = new QVBoxLayout;
	vbox2->addWidget(PinEdit);

 	groupBox2->setLayout(vbox2);

	Layout3->addWidget(groupBox1);
	Layout3->addWidget(groupBox2);

	PageWidget->setLayout(Layout3);

return PageWidget;
}

QWidget* addwizard::CreateGroupPage(void){

QWidget* PageWidget = new QWidget(this);

QVBoxLayout* Layout4 = new QVBoxLayout(this);	
SuperAdmin = new QRadioButton("Hlavní správce");
GroupAdmin = new QRadioButton("Správce oddělení");
StandardUser = new QRadioButton("Uživatelský účet");


GroupSelectBox = new QComboBox;
GroupSelectBox->addItems(*(CurrentUser->GetGroupList()));

Layout4->addWidget(SuperAdmin);
Layout4->addWidget(GroupAdmin);
Layout4->addWidget(StandardUser);
Layout4->addWidget(GroupSelectBox);

PageWidget->setLayout(Layout4);

if(UserRights->GetRights()==PRights::GroupAdmin)
{
SuperAdmin->setEnabled(false);
GroupAdmin->setEnabled(false);
StandardUser->setChecked(true);
GroupSelectBox->setEnabled(false);
GroupSelectBox->setCurrentIndex(UserRights->GetGroup());
}

return PageWidget;
}

void addwizard::RfidToggled(bool on){

if(on)
PinEdit->setFocus();
else
PinEdit->clear();


}

void addwizard::PinToggled(bool on){

if(on)
PinEdit->setFocus();
else
PinEdit->clear();

}

