/*
 * This file is part of libtqtvd_astronav
 *
 * Copyright (C) 2008-2017 TQTVD Software
 * Copyright (C) 2017 Mirakulo Software (mirakulo@mirakulo.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#include "kjs/wk_config.h"
#include "BALConfiguration.h"
#include <font/BTFont.h>
#include "../../Graphics/GraphicManager/BCNativeImageGraphicManager.h"
#include "BCFontPlatformDataPrivateGraphicManager.h"
#include "BTWidget.h"
#include <font/FontData.h>
#include <graphics/GraphicsContext.h>
#include "RGBA32Array.h"

#include "IGraphicManagerAdapter.h"

#include "BTLogHelper.h"

namespace BAL {

class BCNativeImage;

static size_t ucharToUtf8(char * utf8, const UChar * uc, size_t length);

void BTFont::drawGlyphs(GraphicsContext* graphicsContext, const FontData* font, const GlyphBuffer& glyphBuffer,
                      int from, int numGlyphs, const FloatPoint& point) const
{
    DBGML(MODULE_FONTS, LEVEL_INFO, "\nBTFont::drawGlyphs() numGlyphs=%d\n", numGlyphs);
    // Set the text color to use for drawing.
    float red, green, blue, alpha;
    Color penColor = graphicsContext->fillColor();
    penColor.getRGBA(red, green, blue, alpha);

    GlyphBufferGlyph* glyphs = const_cast<GlyphBufferGlyph*>(glyphBuffer.glyphs(from));

	BINativeImage *img = graphicsContext->widget()->backingStore();
	//printf("img=%p\n", img);

	if (!img){
		DBGML(MODULE_FONTS, LEVEL_ERROR, "\nBTFont::drawGlyphs() no IMAGE backing store");
		return;
	}
	BCNativeImage *img2 = static_cast<BCNativeImage *>(img);
	//printf("img2=%p\n", img2);	
	
    IGraphicManagerAdapterSurface* surface = img2->getNativeGraphicManager();
	//printf("surface=%p\n", surface);

    surface->SetColor((int)(red*0xff), (int)(green*0xff), (int)(blue*0xff), (int)(alpha*0xff));
    surface->SetFont(static_cast<BCFontPlatformDataPrivateGraphicManager *> (font->platformData().impl())->getFont ());

    if (letterSpacing() == 0) { // if letterSpacing wasn't set, we can draw all the glyphs at once
        char *encoded = (char *) malloc(sizeof(char) * (numGlyphs * 2));
        if (encoded == 0){
            DBGML(MODULE_FONTS, LEVEL_ERROR, "\nBTFont::drawGlyphs() out of memory");
            return;
        }

        size_t encoded_length = ucharToUtf8(encoded, (const UChar *) glyphs, numGlyphs);
        surface->DrawString(encoded, encoded_length, (int)point.x(), (int)point.y());
        free(encoded);
    }
    else { // otherwise, we need to draw one glyph at a time 
        float offset = 0.0;
        for (int i = 0; i < numGlyphs; i++) {
            char encoded[2];
            size_t encoded_length = ucharToUtf8(encoded, (const UChar *) glyphs + i, 1);
            surface->DrawString(encoded, encoded_length, (int)(point.x() + offset), (int)point.y());

            offset += glyphBuffer.advanceAt(from + i);
        }
    }
}

void BTFont::drawComplexText(GraphicsContext*, const TextRun&, const TextStyle&, const FloatPoint&, int from, int to) const
{
    BALNotImplemented();
}

float BTFont::floatWidthForComplexText(const TextRun&, const TextStyle&) const
{
    BALNotImplemented();
    return 0.0f;
}

int BTFont::offsetForPositionForComplexText(const TextRun&, const TextStyle&, int, bool) const
{
    BALNotImplemented();
    return 0;
}

FloatRect BTFont::selectionRectForComplexText(const TextRun&, const TextStyle&, const IntPoint&, int, int, int) const
{
    BALNotImplemented();
    return FloatRect();
}

static size_t ucharToUtf8(char * utf8, const UChar * uc, size_t length)
{
    size_t i = 0;
    for (size_t j = 0; j < length; j++, i++, uc++) {
        if (UCHAR_IS_LATIN1(*uc)) {
            if (*uc >= LATIN1_PART2_INF)      // Latin-1 supplement (part2)
                utf8[i] = UTF8_ESC2;
            else if (*uc >= LATIN1_PART1_INF) // Latin-1 supplement (part1)
                utf8[i] = UTF8_ESC1;

            utf8[++i] = UCHAR_LATIN1_TO_UTF8(*uc);
#ifdef DEBUG
            printf("*** uc = 0x%04X, utf8[0] = 0x%X, utf8[1] = 0x%X\n", *uc, utf8[i-1], utf8[i]);
#endif
        }
        else if (UCHAR_IS_BASIC_LATIN(*uc) || UCHAR_IS_CONTROL(*uc))
            utf8[i] = *uc; // ignoring byte 1
        else
            utf8[i] = '?'; // unrecognized char 
    }

    return i;
}

}
