#include "XcbTextInterface.h"
#include "XcbLayerInterface.h"
#include "VisualLayer.h"
#include "Color.h"
#include "RectangleElement.h"

#include <string.h>

xcb_gcontext_t XcbTextInterface::GetFontGC(xcb_connection_t  *connection,
        xcb_screen_t *screen, xcb_window_t window, const char* font_name,
        const TextElement* textElement)
{
    xcb_font_t font = xcb_generate_id(connection);
    xcb_open_font(connection, font, strlen(font_name), font_name);

    /* create graphics context */
    xcb_gcontext_t gc = xcb_generate_id(connection);
    uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND | XCB_GC_FONT;
    auto fillColor = XcbLayerInterface::GetColor(textElement->GetFillColor());
    uint32_t value_list[3] = {screen->black_pixel, fillColor, font };

    xcb_create_gc(connection, gc, window, mask, value_list);

    /* close font */
    xcb_close_font(connection, font);
    return gc;
}

void XcbTextInterface::AddTextElement(xcb_connection_t* connection,
        xcb_screen_t* screen, xcb_window_t window,
        const TextElement* textElement)
{
    /* get graphics context */
    auto gc = XcbTextInterface::GetFontGC(connection, screen, window,
            textElement->GetFontLabel().c_str(), textElement);

    /* draw the text */
    const auto content = textElement->GetContent();
    Pixel loc = textElement->GetLocation();
    xcb_image_text_8(connection, content.length(), window, gc,
            loc.GetX(), loc.GetY(), content.c_str());

    /* free the gc */
    xcb_free_gc(connection, gc);
}
