#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qgeneraterandpass.h"

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::MainWindow)
{

  bool CreateTable = 0;
  if(!QFile::exists("db.db")){
      CreateTable = 1;
    }
  //------------------------------------connect to database------------------
  this->db = QSqlDatabase::addDatabase("QSQLITE");
  db.setDatabaseName("db.db");
  if(!db.open()){
      QMessageBox mb;
      mb.setText("Error Connect to DataBasse");
      mb.exec();
      return;
    }
  //------------------------------------connect to database------------------
  if(CreateTable){
      db.exec("CREATE TABLE Data (id INTEGER PRIMARY KEY AUTOINCREMENT, domain VARCHAR (100), login VARCHAR (100), pass VARCHAR (100), info VARCHAR (600));");
      db.exec("CREATE TABLE SPass (pass VARCHAR (100));");
    }

  EnterDialog ed;
  ed.SetPass(&Password);
  if(!ed.exec()){
      QMetaObject::invokeMethod(this, "close", Qt::QueuedConnection);
      return;
    }
  dd.SetPass(Password);

  ui->setupUi(this);
  ui->tableWidget->setColumnCount(3);
 // ui->tableWidget->verticalHeader()->hide();
  ui->tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem(tr("id")));
  ui->tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem(tr("Domain")));
  ui->tableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem(tr("Login")));



  ui->tableWidget->horizontalHeader()->resizeSection(0,0);
  ui->tableWidget->horizontalHeader()->resizeSection(1,260);
  ui->tableWidget->horizontalHeader()->resizeSection(2,180);
  ui->tableWidget->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);

  ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
  ui->tableWidget->setShowGrid(true);
  ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
  connect(ui->tableWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(tableWidgetContextMenu(QPoint)));

  //-----------------------------------------------------//

  ui->checkBox->setChecked(true);
  ui->checkBox_2->setChecked(true);
  ui->checkBox_3->setChecked(true);
  ui->lineEdit_2->setText("10");
  ui->lineEdit_2->setValidator(new QRegExpValidator(QRegExp("^[0-9]{1,100}"), this));
  //-----------------------------------------------------//

  UpdateDataList();




  ui->label_2->setOpenExternalLinks(true);
  ui->label_2->setText("© Djoser | <a href = 'http://djoser-blog.ru'>djoser-blog.ru</a> | email: ");
  QPalette palette;
  QColor color;
  color = ui->lineEdit_3->parentWidget()->palette().color(QPalette::Background);
  palette.setColor(QPalette::Base,color);
  ui->lineEdit_3->setPalette(palette);
  ui->lineEdit_3->setText("djoser.web13.audit@gmail.com");
}

MainWindow::~MainWindow()
{
  delete ui;
}
void MainWindow::on_pushButton_clicked(){
  QGenerateRandPass gp(ui->checkBox->isChecked(),ui->checkBox_2->isChecked(),ui->checkBox_4->isChecked(),ui->checkBox_3->isChecked(),ui->lineEdit_2->text().toInt());
  ui->lineEdit->setText(gp.GeneratePass());
}
void MainWindow::on_pushButton_3_clicked(){


  dd.SetMod(mod_add);
  dd.exec();
  UpdateDataList();
}
void MainWindow::UpdateDataList(){
  ui->tableWidget->clearContents();
  ui->tableWidget->setRowCount(0);
  QSqlQuery query;
  int TWRow = 0;
  QTableWidgetItem *newItem = NULL;

  query.exec("SELECT `id`,`domain`,`login` FROM `Data` ORDER BY `domain` ");
  if(query.record().count()){
      while(query.next()){
          TWRow = this->ui->tableWidget->rowCount();
          this->ui->tableWidget->insertRow(TWRow);
          this->ui->tableWidget->setRowHeight(TWRow, 20);


          newItem = new QTableWidgetItem();
          newItem->setText(query.value(0).toString());
          this->ui->tableWidget->setItem(TWRow,0,newItem);

          newItem = new QTableWidgetItem();
          newItem->setText(query.value(1).toString());
          this->ui->tableWidget->setItem(TWRow,1,newItem);

          newItem = new QTableWidgetItem();
          newItem->setText(query.value(2).toString());
          this->ui->tableWidget->setItem(TWRow,2,newItem);
        }
    }
}
void MainWindow::tableWidgetContextMenu(QPoint pos){

  QList<QTableWidgetItem *> QTW = this->ui->tableWidget->selectedItems();

  if(QTW.length()){
      QMenu * menu = new QMenu(this);

      QAction * CopyDomain = new QAction(tr("Copy Domain"), this);
      QAction * CopyLogin = new QAction(tr("Copy Login"), this);
      QAction * CopyPass = new QAction(tr("Copy Pass"), this);
      QAction * Edit = new QAction(tr("Edit"), this);
      QAction * Delete = new QAction(tr("Delete"), this);


      connect(CopyDomain, SIGNAL(triggered()), this, SLOT(cm_CopyDomain()));
      connect(CopyLogin, SIGNAL(triggered()), this, SLOT(cm_CopyLogin()));
      connect(CopyPass, SIGNAL(triggered()), this, SLOT(cm_CopyPass()));
      connect(Edit, SIGNAL(triggered()), this, SLOT(cm_Edit()));
      connect(Delete, SIGNAL(triggered()), this, SLOT(cm_Delete()));


      menu->addAction(CopyDomain);
      menu->addAction(CopyLogin);
      menu->addAction(CopyPass);
      menu->addAction(Edit);
      menu->addAction(Delete);


      menu->popup(ui->tableWidget->viewport()->mapToGlobal(pos));
    }

}
void MainWindow::cm_CopyPass(){
  QList<QTableWidgetItem *> QTW = this->ui->tableWidget->selectedItems();
  if(QTW.length()){
      QSqlQuery query;
      if(query.exec("SELECT `pass` FROM `Data` WHERE `id` = "+QTW[0]->text())){
          query.next();

          TinyAES crypto;

          QByteArray key = crypto.HexStringToByte(Password);
          QByteArray data = QByteArray::fromBase64(query.value(0).toByteArray());
          data = crypto.Decrypt(data, key);

          QClipboard *clipboard = QApplication::clipboard();
          clipboard->setText(data);
        }
    }
}
void MainWindow::cm_Edit(){
  QList<QTableWidgetItem *> QTW = this->ui->tableWidget->selectedItems();
  if(QTW.length()){
      dd.SetMod(mod_edit);
      dd.SetId(QTW[0]->text());
      dd.exec();
      UpdateDataList();
    }
}
void MainWindow::cm_Delete(){
  QList<QTableWidgetItem *> QTW = this->ui->tableWidget->selectedItems();
  if(QTW.length()){
      QSqlQuery query;
      query.exec("DELETE FROM `Data` WHERE `id` = "+QTW[0]->text());
    }
  UpdateDataList();
}
void MainWindow::cm_CopyLogin(){
  QList<QTableWidgetItem *> QTW = this->ui->tableWidget->selectedItems();
  if(QTW.length()){
      QClipboard *clipboard = QApplication::clipboard();
      clipboard->setText(QTW[2]->text());
    }
}
void MainWindow::cm_CopyDomain(){
  QList<QTableWidgetItem *> QTW = this->ui->tableWidget->selectedItems();
  if(QTW.length()){
      QClipboard *clipboard = QApplication::clipboard();
      clipboard->setText(QTW[1]->text());
    }
}
void MainWindow::on_pushButton_2_clicked(){
  int rows = ui->tableWidget->rowCount();
  QString FindStr = ui->lineEdit_4->text().trimmed();
  bool found = 0;
  for(int i = 0; i < rows; ++i)
  {
      if(ui->tableWidget->item(i, 1)->text() == FindStr)
      {
          ui->tableWidget->selectRow(i);
          found = true;
          break;
      }
  }
  if(!found)
  {
      QMessageBox mb;
      mb.setText("Not Found");
      mb.exec();
  }
}
