/*
    SPDX-FileCopyrightText: 2014-2023 Anne Jan Brouwer <brouwer@annejan.com>
    SPDX-FileCopyrightText: 2018 Lukas Vogel <lukedirtwalker@gmail.com>
    SPDX-FileCopyrightText: 2019 Maciej S. Szmigiero <mail@maciej.szmigiero.name>
    SPDX-FileCopyrightText: 2023 g10 Code GmbH
    SPDX-FileContributor: Sune Stolborg Vuorela <sune@vuorela.dk>

    SPDX-License-Identifier: GPL-3.0-or-later
*/
#include "filecontent.h"

static bool isLineHidden(const QString &line)
{
    return line.startsWith(QStringLiteral("otpauth://"), Qt::CaseInsensitive);
}

FileContent FileContent::parse(const QString &fileContent, const QStringList &templateFields, bool allFields)
{
    QStringList lines = fileContent.split(QLatin1Char('\n'));
    QString password = lines.takeFirst();
    QStringList remainingData, remainingDataDisplay;
    NamedValues namedValues;
    for (const QString &line : qAsConst(lines)) {
        if (line.contains(QLatin1Char(':'))) {
            int colon = line.indexOf(QLatin1Char(':'));
            QString name = line.left(colon);
            QString value = line.right(line.length() - colon - 1);
            if ((allFields && !value.startsWith(QStringLiteral("//"))) // if value startswith // colon is probably from a url
                || templateFields.contains(name)) {
                namedValues.append({name.trimmed(), value.trimmed()});
                continue;
            }
        }

        remainingData.append(line);
        if (!isLineHidden(line))
            remainingDataDisplay.append(line);
    }
    return FileContent(password, namedValues, remainingData.join(QLatin1Char('\n')), remainingDataDisplay.join(QLatin1Char('\n')));
}

QString FileContent::getPassword() const
{
    return this->password;
}

NamedValues FileContent::getNamedValues() const
{
    return this->namedValues;
}

QString FileContent::getRemainingData() const
{
    return this->remainingData;
}

QString FileContent::getRemainingDataForDisplay() const
{
    return this->remainingDataDisplay;
}

FileContent::FileContent(const QString &password, const NamedValues &namedValues, const QString &remainingData, const QString &remainingDataDisplay)
    : password(password)
    , namedValues(namedValues)
    , remainingData(remainingData)
    , remainingDataDisplay(remainingDataDisplay)
{
}

NamedValues::NamedValues()
    : QList()
{
}

NamedValues::NamedValues(std::initializer_list<NamedValue> values)
    : QList(values)
{
}

QString NamedValues::takeValue(const QString &name)
{
    for (int i = 0; i < length(); ++i) {
        if (at(i).name == name) {
            return takeAt(i).value;
        }
    }
    return QString();
}
