/*
 * Copyright (C) 2016 Canonical Ltd.
 * Copyright (C) 2026 UBports Foundation.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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/>.
 *
 * Authored by: James Henstridge <james.henstridge@canonical.com>
 */

#include "item_id.h"

#include <QStringList>
#include <QUrl>
#include <lomiri/storage/provider/Exceptions.h>

using namespace std;
using namespace lomiri::storage::provider;

std::string id_to_remote_path(string const& item_id)
{
    if (item_id.empty())
    {
        throw InvalidArgumentException("Invalid blank item ID");
    }
    if (item_id == ".")
    {
        return string();
    }
    // Decode percent-escapes and reject attempts to escape remote root.
    QString decoded = QUrl::fromPercentEncoding(
        QByteArray::fromStdString(item_id));
    if (decoded[0] == '/')
    {
        throw InvalidArgumentException("Invalid item ID: " + item_id);
    }
    for (auto const& segment : decoded.split('/'))
    {
        if (segment == "." || segment == "..")
        {
            throw InvalidArgumentException("Invalid item ID: " + item_id);
        }
    }

    // Strip the trailing slash used to mark folders
    string path = decoded.toStdString();
    if (path.ends_with('/')) path.pop_back();

    return path;
}

std::string parent_of(string const& item_id)
{
    // Ignore a folder's own trailing slash.
    string id = item_id;
    if (id.size() > 1 && id.ends_with('/')) id.pop_back();

    auto pos = id.rfind('/');
    if (pos == string::npos) return ".";
    return id.substr(0, pos + 1);
}

std::string name_of(string const& item_id)
{
    // Ignore a folder's own trailing slash.
    string id = item_id;
    if (id.size() > 1 && id.ends_with('/')) id.pop_back();
    
    auto pos = id.rfind('/');
    string tail = (pos == string::npos) ? id : id.substr(pos + 1);
    return QUrl::fromPercentEncoding(QByteArray::fromStdString(tail)).toStdString();
}

// Construct a possible ID for a named child of a parent ID
string make_child_id(string const& parent_id, string const& name, bool is_folder)
{
    if (name == "." || name == "..")
    {
        throw InvalidArgumentException("Invalid name: " + name);
    }

    string item_id = parent_id;
    if (item_id == ".")
    {
        item_id.clear();
    }
    else if (item_id.size() == 0 || item_id[item_id.size()-1] != '/')
    {
        item_id += '/';
    }
    item_id += QUrl::toPercentEncoding(QString::fromStdString(name)).toStdString();

    if (is_folder)
    {
        item_id += '/';
    }

    return item_id;
}

bool is_folder(string const& item_id)
{
    auto size = item_id.size();
    if (size == 0)
    {
        throw InvalidArgumentException("Invalid blank item ID");
    }
    if (size == 1 && item_id[0] == '.')
    {
        return true;
    }
    return item_id[size-1] == '/';
}
