#include "enterdialog.h"

EnterDialog::EnterDialog()
{

  wid->setGeometry(0,0,370,50);
  Label.setParent(wid);
  LineEdit.setParent(wid);
  Button.setParent(wid);

  Label.setGeometry(10,10,100,16);
  QSqlQuery query;
  if(query.exec("SELECT count(`pass`) FROM `SPass`")){
      query.next();
      if(query.value(0).toInt()){
          Label.setText("Введите пароль:");
        }else{
          Label.setText("Установить пароль:");
        }
    }else{
      Label.setText("Установить пароль:");
    }

  LineEdit.setGeometry(115,10,180,20);
  Button.setGeometry(300,10,60,20);
  Button.setText("Enter");
  connect(&Button,SIGNAL(clicked(bool)),this,SLOT(on_pushButton_clicked()));

}
void EnterDialog::on_pushButton_clicked(){
  QSqlQuery query;
  QByteArray temp;
  TinyAES crypto;

  QByteArray key;
  QByteArray data;


  if(query.exec("SELECT count(`pass`)cnt, `pass` FROM `SPass`")){
      query.next();
      if(query.value(0).toInt()){

          temp = LineEdit.text().toLocal8Bit();
          data = temp;
          temp = QByteArray(QCryptographicHash::hash(temp,QCryptographicHash::Md5).toHex());
          *lp_pass = temp;
          key = crypto.HexStringToByte(temp);
          temp = query.value(1).toByteArray();
          temp = QByteArray::fromBase64(temp);
          temp = crypto.Decrypt(temp, key);
          if(temp == data){
              accept();
            }

        }else{
          temp = LineEdit.text().trimmed().toLocal8Bit();
          data = temp;
          temp = QByteArray(QCryptographicHash::hash(temp,QCryptographicHash::Md5).toHex());
          *lp_pass = temp;
          key = crypto.HexStringToByte(temp);
          data = crypto.Encrypt(data, key).toBase64();

          query.exec("INSERT INTO `SPass`(`pass`) VALUES ('"+data+"')");
          accept();
        }
    }
}
void EnterDialog::SetPass(QString * _val){
  lp_pass = _val;
}
