/*
 * Copyright © 2013 Canonical Ltd.
 * Copyright © 2023 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "app_manager_mock.h"
#include "test_harness.h"
#include "../cross_process_sync.h"
#include "../fork_and_run.h"

#include <com/lomiri/content/hub.h>
#include <com/lomiri/content/item.h>
#include <com/lomiri/content/peer.h>
#include <com/lomiri/content/scope.h>
#include <com/lomiri/content/store.h>
#include <com/lomiri/content/transfer.h>
#include <com/lomiri/content/type.h>

#include "com/lomiri/content/detail/peer_registry.h"
#include "com/lomiri/content/detail/service.h"
#include "com/lomiri/content/serviceadaptor.h"

#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <QCoreApplication>
#include <QtDBus/QDBusConnection>
#include <QStandardPaths>
#include <QTemporaryDir>
#include <QtTest/QTest>

#include <thread>

namespace cua = com::lomiri::ApplicationManager;
namespace cuc = com::lomiri::content;
namespace cucd = com::lomiri::content::detail;

void PrintTo(const QString& s, ::std::ostream* os) {
    *os << std::string(qPrintable(s));
}

namespace
{
QString service_name{"com.lomiri.content.dbus.Service"};

struct MockedPeerRegistry : public cucd::PeerRegistry
{
    MockedPeerRegistry() : cucd::PeerRegistry()
    {
        using namespace ::testing;

        ON_CALL(*this, default_source_for_type(_)).WillByDefault(Return(cuc::Peer::unknown()));
        ON_CALL(*this, install_default_source_for_type(_,_)).WillByDefault(Return(false));
        ON_CALL(*this, install_source_for_type(_,_)).WillByDefault(Return(false));
    }

    MOCK_METHOD1(default_source_for_type, cuc::Peer(cuc::Type t));
    MOCK_METHOD1(enumerate_known_peers, void(const std::function<void(const cuc::Peer&)>&));
    MOCK_METHOD2(enumerate_known_sources_for_type, void(cuc::Type, const std::function<void(const cuc::Peer&)>&));
    MOCK_METHOD2(enumerate_known_destinations_for_type, void(cuc::Type, const std::function<void(const cuc::Peer&)>&));
    MOCK_METHOD2(enumerate_known_shares_for_type, void(cuc::Type, const std::function<void(const cuc::Peer&)>&));
    MOCK_METHOD2(install_default_source_for_type, bool(cuc::Type, cuc::Peer));
    MOCK_METHOD2(install_source_for_type, bool(cuc::Type, cuc::Peer));
    MOCK_METHOD2(install_destination_for_type, bool(cuc::Type, cuc::Peer));
    MOCK_METHOD2(install_share_for_type, bool(cuc::Type, cuc::Peer));
    MOCK_METHOD1(remove_peer, bool(cuc::Peer));
    MOCK_METHOD1(peer_is_legacy, bool(QString));
};
}

TEST(Hub, transfer_legacy_store_migration)
{
    using namespace ::testing;

    test::CrossProcessSync sync;

    QTemporaryDir home_dir;
    QString home_path = home_dir.path();
    qputenv("HOME", home_path.toLocal8Bit());

    auto parent = [&sync]()
    {
        int argc = 0;
        QCoreApplication app{argc, nullptr};

        QString default_peer_id{"com.does.not.exist.anywhere.application"};

        QDBusConnection connection = QDBusConnection::sessionBus();

        auto mock = new ::testing::NiceMock<MockedPeerRegistry>{};
        EXPECT_CALL(*mock, default_source_for_type(_)).
        Times(AtLeast(1)).
        WillRepeatedly(Return(cuc::Peer{default_peer_id}));

        QSharedPointer<cucd::PeerRegistry> registry{mock};
        auto app_manager = QSharedPointer<cua::ApplicationManager>(new MockedAppManager());
        cucd::Service implementation(connection, registry, app_manager, &app);
        new ServiceAdaptor(std::addressof(implementation));

        connection.registerService(service_name);
        connection.registerObject("/", std::addressof(implementation));

        QObject::connect(&app, &QCoreApplication::aboutToQuit, [&](){
            connection.unregisterObject("/");
            connection.unregisterService(service_name);
        });

        // Make sure we signal readiness after the event loop has started.
        QTimer::singleShot(0 /* msec */, [&sync]() { sync.signal_ready(); });

        app.exec();
    };

    auto child = [&sync]()
    {
        int argc = 0;
        QCoreApplication app(argc, nullptr);

        auto app_pkg = QStringLiteral("somepkg.contenthub");
        auto app_name = QStringLiteral("application");
        app.setOrganizationName(app_pkg);
        app.setApplicationName(app_name);
        qputenv("APP_ID", QStringLiteral("%1_%2_0.1")
                            .arg(app_pkg)
                            .arg(app_name)
                            .toLocal8Bit());
        sync.wait_for_signal_ready();

        test::TestHarness harness;
        harness.add_test_case([]()
        {
            auto hub = cuc::Hub::Client::instance();

            /* [Test aborting hand-crafted store] */
            {
                auto transfer = hub->create_import_from_peer(
                    hub->default_source_for_type(cuc::Type::Known::pictures()));

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
                cuc::Store handcrafted_store("/nonexistent");
                transfer->setStore(&handcrafted_store);
#pragma GCC diagnostic pop

                EXPECT_EQ(transfer->state(), cuc::Transfer::aborted);

                // Just in case
                transfer->abort();
                delete transfer;
            }

            /* [Test store path migration] */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
            auto store_app = hub->store_for_scope_and_type(
                cuc::Scope::app, cuc::Type::Known::pictures());
#pragma GCC diagnostic pop

            QDir store_app_dir(store_app->uri());
            store_app_dir.mkpath(".");

            QFile test_file(store_app_dir.filePath("testMigration"));
            test_file.open(QIODevice::WriteOnly);
            test_file.close();

            ASSERT_TRUE(test_file.exists());

            // Test twice for idempotency.
            for (int i = 0; i < 2; i++) {
                auto transfer = hub->create_import_from_peer(
                    hub->default_source_for_type(cuc::Type::Known::pictures()));

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
                transfer->setStore(store_app);
#pragma GCC diagnostic pop

                auto store_service = transfer->store();
                EXPECT_NE(store_app->uri(), store_service.uri());

                // QFile::symLinkTarget() "returns an empty string if the fileName
                // does not correspond to a symbolic link".
                EXPECT_EQ(QFile::symLinkTarget(store_app->uri()), store_service.uri());

                EXPECT_TRUE(test_file.exists());
                EXPECT_TRUE(QFile::exists(store_service.uri() + "/testMigration"));

                transfer->abort();
                delete transfer;
            }

            hub->quit();
        });
        EXPECT_EQ(0, QTest::qExec(std::addressof(harness)));

        return testing::Test::HasFailure();
    };

    EXPECT_EQ(EXIT_SUCCESS, test::fork_and_run(child, parent));
}
