#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 hl.dsp.focus({ workspace = '1' })"); // no OK: we might be on 1 already

    OK(getFromSocket("/eval hl.workspace_rule({ workspace = '5', monitor = 'HEADLESS-2', persistent = true })"));
    OK(getFromSocket("/eval hl.workspace_rule({ workspace = '6', monitor = 'HEADLESS-PERSISTENT-TEST', persistent = true })"));
    OK(getFromSocket("/eval hl.workspace_rule({ workspace = 'name:PERSIST', monitor = 'HEADLESS-PERSISTENT-TEST', persistent = true })"));
    OK(getFromSocket("/eval hl.workspace_rule({ workspace = 'name:PERSIST-2', monitor = 'HEADLESS-PERSISTENT-TEST', persistent = true })"));

    {
        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 hl.dsp.focus({ monitor = '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)
