/*
 * Copyright (C) 2023 Uniontech Software Technology Co., Ltd.
 *
 * Author:     gongheng<gongheng@uniontech.com>
 *
 * Maintainer: gongheng<gongheng@uniontech.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "tpmoperator.h"
#include "tpmwork.h"
#include "vaultglobaldefine.h"

#include <QDebug>

TPMOperator::~TPMOperator()
{
    workerThread.quit();
    workerThread.wait();
}

TPMOperator *TPMOperator::instance()
{
    static TPMOperator ins;
    return &ins;
}

bool TPMOperator::checkTPMAvailable()
{
    TPMWork work;
    return work.checkTPMAvailable();
}

bool TPMOperator::getRandom(int size, QString &output)
{
    TPMWork work;
    work.getRandom(size, output);

    // Determine whether the password is a hexadecimal character
    int count = output.size();
    if (count != size) {
        qCritical() << QString("Vault error: random password create error! The error password is %1").arg(output);
        return false;
    }
    for (int i =0; i< count; ++i) {
        if (!((output[i] >= '0' && output[i] <= '9') || (output[i] >= 'a' && output[i] <= 'f'))) {
            qCritical() << QString("Vault error: random password create error! The error password is %1").arg(output);
            return false;
        }
    }
    return true;
}

bool TPMOperator::isSupportAlgo(const QString &algoName)
{
    if (algoName.isEmpty())
        return false;

    TPMWork work;
    return work.isSupportAlgo(algoName);
}

void TPMOperator::asynEncrypt(const QString hashAlgo, const QString keyAlgo, const QString keyPin, const QString password)
{
    emit sigStartAsynEncrypt(hashAlgo, keyAlgo, keyPin, password);
}

void TPMOperator::asynDecrypt(const QString &keyPin)
{
    emit sigStartAsynDecrypt(keyPin);
}

TPMOperator::TPMOperator(QObject *parent)
    : QObject(parent)
{
    TPMWork *worker = new TPMWork;
    worker->moveToThread(&workerThread);
    connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
    connect(this, &TPMOperator::sigStartAsynEncrypt, worker, &TPMWork::slotDoEncrypt, Qt::QueuedConnection);
    connect(worker, &TPMWork::sigEncryptFinished, this, &TPMOperator::sigAsynEncryptFinished);
    connect(this, &TPMOperator::sigStartAsynDecrypt, worker, &TPMWork::slotDoDecrypt, Qt::QueuedConnection);
    connect(worker, &TPMWork::sigDecryptFinished, this, &TPMOperator::sigAsynDecryptFinished);
    workerThread.start();
}
