/*
 * clipboard.hpp
 * Simple plain-text clipboard helpers for MontaukOS GUI apps
 * Copyright (c) 2026 Daniel Hammer
 */

#pragma once

#include <montauk/syscall.h>
#include <montauk/string.h>
#include <montauk/heap.h>

namespace gui {

    inline bool clipboard_set_text(const char* text, int len) {
        if (len < 0) return false;
        if (len > 0 && text == nullptr) return false;
        return montauk::clipboard_set_text(text, (uint32_t)len) == 0;
    }

    inline bool clipboard_set_text(const char* text) {
        return clipboard_set_text(text, text ? montauk::slen(text) : 0);
    }

    inline bool clipboard_get_info(Montauk::ClipboardInfo* out) {
        if (out == nullptr) return false;
        return montauk::clipboard_get_info(out) == 0;
    }

    inline bool clipboard_has_text() {
        Montauk::ClipboardInfo info = {};
        return clipboard_get_info(&info) && info.textBytes > 0;
    }

    inline char* clipboard_get_text_alloc(int* out_len = nullptr, uint64_t* out_serial = nullptr) {
        if (out_len) *out_len = 0;
        if (out_serial) *out_serial = 0;

        Montauk::ClipboardInfo info = {};
        if (!clipboard_get_info(&info) || info.textBytes == 0)
            return nullptr;

        uint32_t cap = info.textBytes + 1;
        char* text = (char*)montauk::malloc(cap);
        if (text == nullptr) return nullptr;

        uint32_t actual_len = 0;
        uint64_t serial = 0;
        if (montauk::clipboard_get_text(text, info.textBytes, &actual_len, &serial) != 0 ||
            actual_len > info.textBytes) {
            montauk::mfree(text);
            return nullptr;
        }

        text[actual_len] = '\0';
        if (out_len) *out_len = (int)actual_len;
        if (out_serial) *out_serial = serial;
        return text;
    }

    inline bool clipboard_clear() {
        return montauk::clipboard_clear() == 0;
    }

}
