/*
 * Copyright (C) 2025 UBports Foundation
 *
 * 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; version 3.
 *
 * 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/>.
 *
 * Authors: Alfred Neumayer <alfred@ubports.com>
 */

#include "questionaire.h"
#include "commandrunner.h"

#include <QDebug>

int Questionaire::run(const std::string& command, const std::string& password, const Questionaire::Questions& questions)
{
    CommandRunner runner;
    QObject::connect(&runner, &CommandRunner::passwordRequested, [=, &runner](){
        qDebug() << "Password requested (questionaire)";
        const auto qpassword = QString::fromStdString(password);
        runner.writeInput(qpassword);
    });
    QObject::connect(&runner, &CommandRunner::outputReceived, [=, &questions, &runner](const QString& output){
        qDebug() << "Output:" << output;
        for (const auto& question : questions) {
            auto qNeedle = QString::fromStdString(question.needle);
            if (output.contains(qNeedle)) {
                qDebug() << "Needle found in haystack";
                const auto answer = question.answer(output.toStdString());
                if (answer.empty())
                    return;

                runner.writeInput(QString::fromStdString(answer));
                return;
            }
        }
    });

    const auto splitCmd = QString::fromStdString(command).split(" ", Qt::SkipEmptyParts);
    return runner.sudo(splitCmd, true);
}
