#include "tests.hpp"
#include "../../shared.hpp"
#include "../../hyprctlCompat.hpp"
#include <print>
#include <thread>
#include <chrono>
#include <hyprutils/os/Process.hpp>
#include <hyprutils/memory/WeakPtr.hpp>
#include <csignal>
#include <cerrno>
#include "../shared.hpp"

static int ret = 0;

using namespace Hyprutils::OS;
using namespace Hyprutils::Memory;

#define UP CUniquePointer
#define SP CSharedPointer

static bool test() {
    NLog::log("{}Testing persistent workspaces", Colors::GREEN);

    EXPECT(Tests::windowCount(), 0);

    // test on workspace "window"
    NLog::log("{}Switching to workspace 1", Colors::YELLOW);
    getFromSocket("/dispatch workspace 1"); // no OK: we might be on 1 already

    OK(getFromSocket("/keyword workspace 5, monitor:HEADLESS-2, persistent:1"));
    OK(getFromSocket("/keyword workspace 6, monitor:HEADLESS-PERSISTENT-TEST, persistent:1"));
    OK(getFromSocket("/keyword workspace name:PERSIST, monitor:HEADLESS-PERSISTENT-TEST, persistent:1"));
    OK(getFromSocket("/keyword workspace name:PERSIST-2, monitor:HEADLESS-PERSISTENT-TEST, persistent:1"));

    {
        auto str = getFromSocket("/workspaces");
        EXPECT_CONTAINS(str, "ID 5 (5)");
        EXPECT_COUNT_STRING(str, "workspace ID ", 2);
    }

    OK(getFromSocket("/output create headless HEADLESS-PERSISTENT-TEST"));

    {
        auto str = getFromSocket("/monitors");
        EXPECT_CONTAINS(str, "HEADLESS-PERSISTENT-TEST");
    }

    OK(getFromSocket("/dispatch focusmonitor HEADLESS-PERSISTENT-TEST"));

    {
        auto str = getFromSocket("/workspaces");
        EXPECT_CONTAINS(str, "ID 2 (2)"); // this should be automatically generated by hl
        EXPECT_CONTAINS(str, "ID 5 (5)");
        EXPECT_CONTAINS(str, "ID 6 (6)");
        EXPECT_CONTAINS(str, "(PERSIST) on monitor");
        EXPECT_CONTAINS(str, "(PERSIST-2) on monitor");
        EXPECT_COUNT_STRING(str, "workspace ID ", 6);
    }

    OK(getFromSocket("/reload"));

    {
        auto str = getFromSocket("/workspaces");
        EXPECT_NOT_CONTAINS(str, "ID 5 (5)");
        EXPECT_NOT_CONTAINS(str, "ID 6 (6)");
        EXPECT_NOT_CONTAINS(str, "(PERSIST) on monitor");
        EXPECT_COUNT_STRING(str, "workspace ID ", 2);
    }

    OK(getFromSocket("/output remove HEADLESS-PERSISTENT-TEST"));

    // kill all
    NLog::log("{}Killing all windows", Colors::YELLOW);
    Tests::killAllWindows();

    NLog::log("{}Expecting 0 windows", Colors::YELLOW);
    EXPECT(Tests::windowCount(), 0);

    // reload cfg
    OK(getFromSocket("/reload"));

    return !ret;
}

REGISTER_TEST_FN(test)
