//#include "mainwindow.h"
#include "password.h"
#include <qt5keychain/keychain.h>
#include <qt5keychain/qkeychain_export.h>
#include <QSettings>
#include "tools.h"

using namespace std;
extern QApplication a;

QString appName = "RsyncUI";

static QSettings sett{appName, appName};

void setPassword(QString account, QString pass)
{
	QKeychain::WritePasswordJob write(appName);
	write.setSettings(&sett);
	write.setKey(account);
	write.setTextData(pass);

	QEventLoop loop;
	write.connect(&write, &QKeychain::WritePasswordJob::finished, &loop, &QEventLoop::quit);

	write.start();
	loop.exec();

	if(write.error())
		info(DEBUGMACRO, "Error writing key1. Error: " + write.errorString());
}

QString getPassword(const QString& name)
{
	QKeychain::ReadPasswordJob readPass(appName);
	readPass.setSettings(&sett);
	readPass.setKey(name);

	QEventLoop loop;
	readPass.connect(&readPass, &QKeychain::ReadPasswordJob::finished, &loop, &QEventLoop::quit);

	readPass.start();
	loop.exec();

	if(readPass.error())
	{
		info(DEBUGMACRO, "KeyHandler~Error reading decrypt Pass. Error: " + readPass.errorString());
		return "";
	}else
	{
		QString data = readPass.textData();
		return data;
	}
}
