#define TEXT_C

#include <windows.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "filter.h"
#include "text.h"

void show_text(char *text, PIXEL_YC *dst, int w, int h, int step, PIXEL *bg, PIXEL *fg, EXFUNC *func);

static void get_text_box_size(HDC dc, char *text, SIZE *size);

/*----------------------------------------------------------------*/
void show_text(char *text, PIXEL_YC *dst, int w, int h, int step, PIXEL *bg, PIXEL *fg, EXFUNC *func)
{
	int i,n;
	int offset;
	HDC dc;
	HBITMAP bmp;
	BITMAPINFO bmi;
	char *data,*line;
	RECT rc;
	COLORREF color;
	HBRUSH brush;
	SIZE size;

	dc = CreateCompatibleDC(GetDC(NULL));
	SelectObject(dc, GetStockObject(DEFAULT_GUI_FONT));

	get_text_box_size(dc, text, &size);

	size.cx += 4;
	size.cy += 4;

	offset = 0;
	if(size.cx < w){
		offset = (w-size.cx)/2;
		w = size.cx;
	}
	if(size.cy < h){
		offset += (h-size.cy)/2*step;
		h = size.cy;
	}
	
	bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	bmi.bmiHeader.biWidth = w;
	bmi.bmiHeader.biHeight = h;
	bmi.bmiHeader.biPlanes = 1;
	bmi.bmiHeader.biBitCount = 24;
	bmi.bmiHeader.biCompression = BI_RGB;
	bmi.bmiHeader.biSizeImage = 0;
	bmi.bmiHeader.biXPelsPerMeter = 3800;
	bmi.bmiHeader.biYPelsPerMeter = 3800;
	bmi.bmiHeader.biClrUsed = 0;
	bmi.bmiHeader.biClrImportant = 0;

	bmp = CreateDIBSection(dc, &bmi, DIB_RGB_COLORS, &data, NULL, 0);
	SelectObject(dc, bmp);

	color = ((bg->b & 0xff) << 16) | ((bg->g & 0xff) << 8) | (bg->r & 0xff);
	brush = CreateSolidBrush(color);
	SetRect(&rc, 0, 0, w, h);
	FillRect(dc, &rc, brush);
	DeleteObject(brush);
	SetBkColor(dc, color);

	color = ((fg->b & 0xff) << 16) | ((fg->g & 0xff) << 8) | (fg->r & 0xff);
	SetTextColor(dc, color);
	
	SetRect(&rc, 2, 2, w-4, h-4);
	DrawText(dc, text, -1, &rc, DT_EXPANDTABS|DT_NOPREFIX);

	n = (w*3+3)/4*4;
	dst += offset;
	for(i=0,line=data+n*(h-1);i<h;i++){
		func->rgb2yc(dst, (PIXEL *)line, w);
		line -= n;
		dst += step;
	}

	DeleteObject(bmp);
	DeleteDC(dc);
}

/*----------------------------------------------------------------*/
static void get_text_box_size(HDC dc, char *text, SIZE *size)
{
	int n;
	char *p,*head;
	SIZE work;

	p = text;
	head = p;

	memset(size, 0, sizeof(SIZE));

	while(p[0]){
		if(p[0] == '\n'){
			n = p-head+1;
			GetTextExtentPoint32(dc, head, n, &work);
			if(work.cx > size->cx){
				size->cx = work.cx;
			}
			size->cy += work.cy;
			head = p+1;
		}
		p = CharNext(p);
	}
	n = strlen(head);
	if(n){
		GetTextExtentPoint32(dc, head, n, &work);
		if(work.cx > size->cx){
			size->cx = work.cx;
		}
		size->cy += work.cy;
	}

	size->cx+=2;
	size->cy+=2;
}


