#include "XcbLayerInterface.h"

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

#include <memory>

uint32_t XcbLayerInterface::GetColor(const Color* color)
{
    return XcbLayerInterface::GetColor(color->GetR(),
            color->GetG(), color->GetB());
}

uint32_t XcbLayerInterface::GetColor(int r, int g, int b)
{
    return b + (g<<8) + (r<<16);
}

void XcbLayerInterface::ModifyGcColor(xcb_connection_t* connection, xcb_gcontext_t gc,
        const Color* color)
{
    uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_GRAPHICS_EXPOSURES;
    uint32_t values[2] = {XcbLayerInterface::GetColor(color), 0};

    xcb_change_gc(connection, gc, mask, values);
}

void XcbLayerInterface::AddLayer(xcb_connection_t* connection,
        xcb_screen_t* screen, xcb_window_t window, xcb_gcontext_t gc,
        VisualLayer* layer)
{
    if(layer->HasText())
    {
        XcbTextInterface::AddTextElement(connection, screen, window, layer->GetText());
    }
    else if(layer->HasShape())
    {
        auto shape = layer->GetShape();
        if(shape->GetType() == GeometryElement::Type::Rectangle)
        {
            const auto rectangle = dynamic_cast<RectangleElement*>(shape);
            const auto loc = rectangle->GetLocation();
            const auto width = static_cast<uint16_t>(rectangle->GetWidth());
            const auto height = static_cast<uint16_t>(rectangle->GetHeight());
            xcb_rectangle_t rectangles[] = { { static_cast<int16_t>(loc.GetX()),
                    static_cast<int16_t>(loc.GetY()), width, height} };
            XcbLayerInterface::ModifyGcColor(connection, gc, rectangle->GetFillColor());
            xcb_poly_fill_rectangle(connection, window, gc, 1, rectangles);
        }
    }
}

