#include "DirectXTextPainter.h"

#include "DrawingContext.h"
#include "DrawingSurface.h"

#include "FontsManager.h"
#include "FontGlyph.h"

#include "TextData.h"
#include "SceneText.h"
#include "DirectX2dInterface.h"

#include "UnicodeUtils.h"
#include "File.h"

#include "Win32BaseIncludes.h"

#include <d2d1_3.h>
#include <d2d1_1.h>
#include <dwrite.h>

DirectXTextPainter::DirectXTextPainter()
{

}

void DirectXTextPainter::setD2dInterface(DirectX2dInterface* d2dIterface)
{
    mD2dInterface = d2dIterface;
    mD2dInterface->getRenderTarget()->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &mTextBrush);
}

void DirectXTextPainter::updateTextFormat(SceneText* text)
{
    mD2dInterface->getDirectWriteFactory()->CreateTextFormat(
        UnicodeUtils::utf8ToUtf16WString(text->getTextData().mFont.getFaceName()).c_str(),
        nullptr,
        DWRITE_FONT_WEIGHT_NORMAL,
        DWRITE_FONT_STYLE_NORMAL,
        DWRITE_FONT_STRETCH_NORMAL,
        static_cast<float>(text->getTextData().mFont.getSize()),
        L"en-us",
        &mTextFormat
    );
    mTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
    mTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);

    mTextBrush->SetColor(toD2dColor(text->getSolidMaterial().getFillColor()));
}

D2D1::ColorF DirectXTextPainter::toD2dColor(const Color& color)
{
    return D2D1::ColorF(static_cast<float>(color.getR() / 255.0), static_cast<float>(color.getG() / 255.0),
        static_cast<float>(color.getB() / 255.0), static_cast<float>(color.getAlpha()));
}

void DirectXTextPainter::paint(SceneText* text, DrawingContext* context)
{
    const auto location = text->getTransform().getLocation();

    const auto width = static_cast<float>(text->getTextWidth());
    const auto height = static_cast<float>(text->getTextHeight());

    D2D1_RECT_F textRect = D2D1::RectF(static_cast<float>(location.getX()), static_cast<float>(location.getY()), static_cast<float>(location.getX() + width), static_cast<float>(location.getY() + height));

    updateTextFormat(text);

    auto content = UnicodeUtils::utf8ToUtf16WString(text->getTextData().mContent);

    mD2dInterface->getRenderTarget()->DrawText(content.c_str(), static_cast<UINT32>(content.size()), mTextFormat.Get(), &textRect, mTextBrush.Get());
}



