/*
 * This file is part of smolbote. It's copyrighted by the contributors recorded
 * in the version control history of the file, available from its original
 * location: https://neueland.iserlohn-fortress.net/gitea/aqua/smolbote
 *
 * SPDX-License-Identifier: GPL-3.0
 */

#include "wallet.h"
#include <QWebEngineView>

#ifdef PLASMA
#include <kwallet.h>
#endif

void Wallet::autocompleteForm(QWebEngineView *view)
{
#ifdef PLASMA
    const auto findFormFunction = QLatin1Literal("index = undefined; for(var i = 0; i < document.forms.length; ++i) { if(document.forms[i].autocomplete) { index = i } }; index");
    view->page()->runJavaScript(findFormFunction, [view](const QVariant &v) {
        if(!v.isNull()) {
            auto autofillFunction = QString("inputs = document.forms[%1].getElementsByTagName('input');"
                                            "for(var i = 0; i < inputs.length; ++i) {"
                                            "  if(inputs[i].type == 'email') { inputs[i].value='%2' }"
                                            "  if(inputs[i].type == 'password') { inputs[i].value='%3' }"
                                            "}");

            auto *wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet(), view->window()->winId());
            if(wallet) {
                wallet->setFolder("smolbote");
                QMap<QString, QString> map;
                wallet->readMap(view->url().host(), map);
                qDebug() << map;

                const auto username = map.firstKey();
                QString password;
                wallet->readPassword(map.value(username), password);
                view->page()->runJavaScript(autofillFunction.arg(v.toString(), username, password));
            }
            delete wallet;
        }
    });
#endif
}