void RouterKeygen::onNetworkReply(QNetworkReply* reply){
    const unsigned int RESPONSE_OK = 200;
    if ( !automaticUpdateCheck ){
        cleanLoadingAnimation();
        enableUI(true);
    }
    if(reply->error() == QNetworkReply::NoError)
    {
        unsigned int httpstatuscode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt();
        switch(httpstatuscode)
        {
        case RESPONSE_OK:
            if (reply->isReadable())
            {
                 QByteArray result;
                 result = reply->readAll();

                 QScriptValue sc;
                 QScriptEngine engine;
                 sc = engine.evaluate("(" +QString(result) + ")");
                 QString version = sc.property("version").toString();
                if ( version == QApplication::applicationVersion() ){
                    if ( !automaticUpdateCheck ){
                        ui->statusBar->showMessage(tr("The application is already at the latest version."));
                    }
                }
                else{
                    //TODO: when the final website is sc.property("url").toString()
                    UpdateDialog * updateDialog = new UpdateDialog(QString("https://code.google.com/p/android-thomson-key-solver/downloads/list"),
                                                                   version, this);
                    updateDialog->show();
                }
            }
            break;
        default:
            if ( !automaticUpdateCheck ){
                ui->statusBar->showMessage(tr("Error while checking for updates"));
            }
            break;
        }
    }
    else {
        if ( !automaticUpdateCheck ){
            ui->statusBar->showMessage(tr("Error while checking for updates"));
        }
    }
    automaticUpdateCheck = false;
    reply->deleteLater();
}
void RouterKeygen::getResults() {
    cleanLoadingAnimation();
    enableUI(true);
    if (calculator->hadError()) {
        ui->statusBar->showMessage(tr("Error while calculating."));
        delete calculator;
        calculator = NULL;
        return;
    }
    listKeys = this->calculator->getResults();
    if (listKeys.isEmpty()) {
        ui->statusBar->showMessage(tr("No keys were calculated."));
        delete calculator;
        calculator = NULL;
        return;
    }
    ui->passwordsList->clear();
    for (int i = 0; i < listKeys.size(); ++i)
        ui->passwordsList->insertItem(0, listKeys.at(i));
    ui->statusBar->showMessage(tr("Calculation finished"));
    delete calculator;
    calculator = NULL;
}
void RouterKeygen::getResults() {
	cleanLoadingAnimation();
	ui->calculateButton->setEnabled(true);
	ui->refreshScan->setEnabled(true);
	if (calculator->hadError()) {
		ui->statusBar->showMessage(tr("Error while calculating."));
		delete calculator;
		calculator = NULL;
		return;
	}
	listKeys = this->calculator->getResults();
	if (listKeys.isEmpty()) {
		ui->statusBar->showMessage(tr("No keys were calculated."));
		delete calculator;
		calculator = NULL;
		return;
	}
	for (int i = 0; i < listKeys.size(); ++i)
		ui->passwordsList->insertItem(0, listKeys.at(i));
	ui->statusBar->showMessage(tr("Calculation finished"));
	ui->passwordsLabel->setText(tr("Calculated Passwords for %1").arg(router->getSsidName()));
	delete calculator;
	calculator = NULL;
}
void RouterKeygen::scanFinished(int code) {
    cleanLoadingAnimation();
    enableUI(true);
    switch (code) {
    case QWifiManager::SCAN_OK: {
            foreach ( QSharedPointer<QScanResult> scanResult, wifiNetworks )
                scanResult.clear();
            bool setTabPosition = false;
            if ( wifiNetworks.size() == 0 )
                setTabPosition = true;
            wifiNetworks = wifiManager->getScanResults();
            //Stting the row count to the maximum possible value
            ui->unsupportedNetworkslist->setRowCount(wifiNetworks.size());
            ui->supportedNetworkslist->setRowCount(wifiNetworks.size());
            ui->unlikelyNetworkslist->setRowCount(wifiNetworks.size());
            trayMenu->clear();
            connect(trayMenu->addAction(tr("Open")),
                    SIGNAL(triggered()), this, SLOT(show()));
            trayMenu->addSeparator();
            connect(trayMenu->addAction(tr("Vulnerable networks")),
                    SIGNAL(triggered()), this, SLOT(show()));
            bool foundVulnerable = false;
            int unsupportedPos = 0, supportedPos = 0, unlikelyPos= 0;
           for (int i = 0; i < wifiNetworks.size(); ++i) {
                wifiNetworks.at(i)->checkSupport(*matcher);
                if ( wifiNetworks.at(i)->getSupportState() == Keygen::UNSUPPORTED ){
                    ui->unsupportedNetworkslist->setItem(unsupportedPos, 0,
                                              new QTableWidgetItem(wifiNetworks.at(i)->getSsidName()));
                    ui->unsupportedNetworkslist->setItem(unsupportedPos, 1,
                                              new QTableWidgetItem(wifiNetworks.at(i)->getMacAddress()));
                    QString level;
                    level.setNum(wifiNetworks.at(i)->getLevel(), 10);
                    ui->unsupportedNetworkslist->setItem(unsupportedPos, 2, new QTableWidgetItem(level));
                    ++unsupportedPos;
                }
                else{
                    if ( wifiNetworks.at(i)->getSupportState() == Keygen::SUPPORTED ){
                        ui->supportedNetworkslist->setItem(supportedPos, 0,
                                                   new QTableWidgetItem(wifiNetworks.at(i)->getSsidName()));
                         ui->supportedNetworkslist->setItem(supportedPos, 1,
                                                   new QTableWidgetItem(wifiNetworks.at(i)->getMacAddress()));
                         QString level;
                         level.setNum(wifiNetworks.at(i)->getLevel(), 10);
                         ui->supportedNetworkslist->setItem(supportedPos, 2, new QTableWidgetItem(level));
                         ++supportedPos;
                    }
                    else {//if ( networks.at(i)->getSupportState() == Keygen::MAYBE )
                         ui->unlikelyNetworkslist->setItem(unlikelyPos, 0,
                                                   new QTableWidgetItem(wifiNetworks.at(i)->getSsidName()));
                         ui->unlikelyNetworkslist->setItem(unlikelyPos, 1,
                                                   new QTableWidgetItem(wifiNetworks.at(i)->getMacAddress()));
                         QString level;
                         level.setNum(wifiNetworks.at(i)->getLevel(), 10);
                         ui->unlikelyNetworkslist->setItem(unlikelyPos, 2, new QTableWidgetItem(level));
                         ++unlikelyPos;
                    }
                    addNetworkToTray(wifiNetworks.at(i)->getSsidName(), wifiNetworks.at(i)->getLevel(), wifiNetworks.at(i)->isLocked());
                    foundVulnerable = true;
                }
            }
            //Stting the row count to the correct value
            ui->unsupportedNetworkslist->setRowCount(unsupportedPos);
            ui->supportedNetworkslist->setRowCount(supportedPos);
            ui->unlikelyNetworkslist->setRowCount(unlikelyPos);
            if ( setTabPosition ){
                if ( supportedPos > 0 )
                    ui->networkSplitter->setCurrentIndex(0);
                else if ( unlikelyPos > 0 )
                    ui->networkSplitter->setCurrentIndex(1);
                else
                    ui->networkSplitter->setCurrentIndex(2);
            }
            if (!foundVulnerable) {
                trayMenu->addAction(tr("None were detected"))->setEnabled(false);
            }

            trayMenu->addSeparator();
            trayMenu->addAction(startUpAction);
            trayMenu->addAction(runInBackgroundAction);
            trayMenu->addSeparator();
            connect(trayMenu->addAction(tr("Quit")), SIGNAL(triggered()), qApp, SLOT(quit()));
            if (wifiNetworks.size() == 0) {
                 ui->statusBar->showMessage(tr("None were detected"));
            }
            QStringList headers;
            headers << tr("Name") << tr("MAC") << tr("Strength");
            ui->supportedNetworkslist->setHorizontalHeaderLabels(headers);
            ui->supportedNetworkslist->resizeColumnsToContents();
            ui->supportedNetworkslist->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
            ui->supportedNetworkslist->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
            ui->supportedNetworkslist->sortByColumn(2); //Order by Strength
            ui->unsupportedNetworkslist->setHorizontalHeaderLabels(headers);
            ui->unsupportedNetworkslist->resizeColumnsToContents();
            ui->unsupportedNetworkslist->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
            ui->unsupportedNetworkslist->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
            ui->unsupportedNetworkslist->sortByColumn(2); //Order by Strength
            ui->unlikelyNetworkslist->setHorizontalHeaderLabels(headers);
            ui->unlikelyNetworkslist->resizeColumnsToContents();
            ui->unlikelyNetworkslist->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
            ui->unlikelyNetworkslist->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
            ui->unlikelyNetworkslist->sortByColumn(2); //Order by Strength
            break;
	}
    case QWifiManager::ERROR_NO_NM:
        ui->statusBar->showMessage(tr("Network Manager was not detected"));
        break;

    case QWifiManager::ERROR_NO_WIFI:
        ui->statusBar->showMessage(tr("No Wifi device detected"));
        break;

    case QWifiManager::ERROR_NO_WIFI_ENABLED:
        ui->statusBar->showMessage(tr("The wifi device is not enabled"));
        break;
    }

}
void RouterKeygen::scanFinished(int code) {
	cleanLoadingAnimation();
	ui->refreshScan->setEnabled(true);
	ui->calculateButton->setEnabled(true);
	switch (code) {
	case QWifiManager::SCAN_OK: {
		ui->networkslist->clear();
		QVector<QScanResult*> networks = wifiManager->getScanResults();
		ui->networkslist->setRowCount(networks.size());
		trayMenu->clear();
		connect(trayMenu->addAction(tr("Vulnerable networks")),
				SIGNAL(triggered()), this, SLOT(show()));
		bool foundVulnerable = false;
		for (int i = 0; i < networks.size(); ++i) {
			ui->networkslist->setItem(i, 0,
					new QTableWidgetItem(networks.at(i)->ssid));
			ui->networkslist->setItem(i, 1,
					new QTableWidgetItem(networks.at(i)->bssid));
			QString level;
			level.setNum(networks.at(i)->level, 10);
			ui->networkslist->setItem(i, 2, new QTableWidgetItem(level));
			Keygen * supported = matcher.getKeygen(networks.at(i)->ssid,
					networks.at(i)->bssid, networks.at(i)->level, networks.at(i)->capabilities);
			if (supported != NULL) {
				ui->networkslist->setItem(i, 3,
						new QTableWidgetItem(tr("Yes")));
				addNetworkToTray(networks.at(i)->ssid, networks.at(i)->level, supported->isLocked());
				foundVulnerable = true;
				delete supported;
			} else
				ui->networkslist->setItem(i, 3, new QTableWidgetItem(tr("No")));
		}
        if (!foundVulnerable) {
            trayMenu->addAction(tr("\tNone were detected"))->setEnabled(false);
		}
		trayMenu->addSeparator();
		QAction * startUp = trayMenu->addAction(tr("Run on Start up"));
		startUp->setCheckable(true);
		startUp->setChecked(runOnStartUp);
		connect(startUp, SIGNAL(toggled(bool)), this,
				SLOT(startUpRunToggle(bool)));
		QAction * backgroundRun = trayMenu->addAction(
				tr("Run in the background"));
		backgroundRun->setCheckable(true);
		backgroundRun->setChecked(runInBackground);
		connect(backgroundRun, SIGNAL(toggled(bool)), this,
				SLOT(backgroundRunToggle(bool)));
		trayMenu->addSeparator();
		QAction * exitAction = trayMenu->addAction(tr("Exit"));
		connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
		QStringList headers;
		headers << "SSID" << "BSSID" << tr("Strength") << tr("Supported");
		ui->networkslist->setHorizontalHeaderLabels(headers);
		ui->networkslist->resizeColumnsToContents();
		ui->networkslist->horizontalHeader()->setStretchLastSection(true);
		ui->networkslist->sortByColumn(2); //Order by Strength
		ui->networkslist->sortByColumn(3); // and then by support
		//ui->statusBar->clearMessage();
		break;
	}
	case QWifiManager::ERROR_NO_NM:
		ui->statusBar->showMessage(tr("Network Manager was not detected"));
		break;

	case QWifiManager::ERROR_NO_WIFI:
		ui->statusBar->showMessage(tr("No Wifi device detected"));
		break;

	case QWifiManager::ERROR_NO_WIFI_ENABLED:
		ui->statusBar->showMessage(tr("The wifi card is not enabled"));
		break;
	}

}