/*
 * 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/>.
 */

#include "LocalVendor.h"
#include "../rclone_ops.h"

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

LocalVendor::LocalVendor(Context const& ctx)
    : path_(boost::get<PasswordCredentials>(ctx.credentials).host)
{
}

bool LocalVendor::is_valid_context(Context const& ctx)
{
    auto const* credentials = boost::get<PasswordCredentials>(&ctx.credentials);
    return credentials && !credentials->host.empty()
        && credentials->host[0] == '/';
}

Context LocalVendor::test_context(string const& path)
{
    Context ctx;
    ctx.credentials = PasswordCredentials{string(), string(), path};
    return ctx;
}

void LocalVendor::get_conn_string(shared_ptr<RcloneClient> const& client,
                                  ConnStringCallback cb)
{
    if (!remote_->empty())
    {
        cb(*remote_ + ":", boost::exception_ptr());
        return;
    }

    string name = next_remote_name("local");
    create_remote(client, name, "alias", {{"remote", path_}},
                  [cb, remote = remote_, name](boost::exception_ptr const& error) {
        if (error)
        {
            cb(string(), error);
            return;
        }
        *remote = name;
        cb(name + ":", boost::exception_ptr());
    });
}
