/* Copyright (C) 2013 G.P. Halkes
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3, as
   published by the Free Software Foundation.

   This program 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdint.h>
#include <string.h>
#include <cairo.h>
#include <pango/pangocairo.h>

#include "window.h"

/* TODO: these should be setable from the command line */
int cell_width = 8, cell_height = 16;
const char *option_font = "DejaVu Sans Mono";

typedef struct {
	const char idx;
	const char *utf8, *alt;
} acs_map_t;

static acs_map_t acs_map[] = {
	{ '}', "\xc2\xa3", "f" }, /* U+00A3 POUND SIGN [1.1] */
	{ '.', "\xe2\x96\xbc", "v" }, /* U+25BC BLACK DOWN-POINTING TRIANGLE [1.1] */
	{ ',', "\xe2\x97\x80", "<" }, /* U+25C0 BLACK LEFT-POINTING TRIANGLE [1.1] */
	{ '+', "\xe2\x96\xb6", ">" }, /* U+25B6 BLACK RIGHT-POINTING TRIANGLE [1.1] */
	{ '-', "\xe2\x96\xb2", "^" }, /* U+25B2 BLACK UP-POINTING TRIANGLE [1.1] */
	{ 'h', "\xe2\x96\x92", "#" }, /* U+2592 MEDIUM SHADE [1.1] */
	{ '~', "\xc2\xb7", "o" }, /* U+00B7 MIDDLE DOT [1.1] */
	{ 'a', "\xe2\x96\x92", ":" }, /* U+2592 MEDIUM SHADE [1.1] */
	{ 'f', "\xc2\xb0", "\\" }, /* U+00B0 DEGREE SIGN [1.1] */
	{ '`', "\xe2\x97\x86", "+" }, /* U+25C6 BLACK DIAMOND [1.1] */
	{ 'z', "\xe2\x89\xa5", ">" }, /* U+2265 GREATER-THAN OR EQUAL TO [1.1] */
	{ '{', "\xcf\x80", "*" }, /* U+03C0 GREEK SMALL LETTER PI [1.1] */
	{ 'q', "\xe2\x94\x80", "-" }, /* U+2500 BOX DRAWINGS LIGHT HORIZONTAL [1.1] */
	/* Should probably be something like a crossed box, for now keep #.
	   - ncurses maps to SNOWMAN!
	   - xterm shows 240B, which is not desirable either
	*/
	{ 'i', "#", "#" },
	{ 'n', "\xe2\x94\xbc", "+" }, /* U+253C BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL [1.1] */
	{ 'y', "\xe2\x89\xa4", "<" }, /* U+2264 LESS-THAN OR EQUAL TO [1.1] */
	{ 'm', "\xe2\x94\x94", "+" }, /* U+2514 BOX DRAWINGS LIGHT UP AND RIGHT [1.1] */
	{ 'j', "\xe2\x94\x98", "+" }, /* U+2518 BOX DRAWINGS LIGHT UP AND LEFT [1.1] */
	{ '|', "\xe2\x89\xa0", "!" }, /* U+2260 NOT EQUAL TO [1.1] */
	{ 'g', "\xc2\xb1", "#" }, /* U+00B1 PLUS-MINUS SIGN [1.1] */
	{ 'o', "\xe2\x8e\xba", "~" }, /* U+23BA HORIZONTAL SCAN LINE-1 [3.2] */
	{ 'p', "\xe2\x8e\xbb", "-" }, /* U+23BB HORIZONTAL SCAN LINE-3 [3.2] */
	{ 'r', "\xe2\x8e\xbc", "-" }, /* U+23BC HORIZONTAL SCAN LINE-7 [3.2] */
	{ 's', "\xe2\x8e\xbd", "_" }, /* U+23BD HORIZONTAL SCAN LINE-9 [3.2] */
	{ '0', "\xe2\x96\xae", "#" }, /* U+25AE BLACK VERTICAL RECTANGLE [1.1] */
	{ 'w', "\xe2\x94\xac", "+" }, /* U+252C BOX DRAWINGS LIGHT DOWN AND HORIZONTAL [1.1] */
	{ 'u', "\xe2\x94\xa4", "+" }, /* U+2524 BOX DRAWINGS LIGHT VERTICAL AND LEFT [1.1] */
	{ 't', "\xe2\x94\x9c", "+" }, /* U+251C BOX DRAWINGS LIGHT VERTICAL AND RIGHT [1.1] */
	{ 'v', "\xe2\x94\xb4", "+" }, /* U+2534 BOX DRAWINGS LIGHT UP AND HORIZONTAL [1.1] */
	{ 'l', "\xe2\x94\x8c", "+" }, /* U+250C BOX DRAWINGS LIGHT DOWN AND RIGHT [1.1] */
	{ 'k', "\xe2\x94\x90", "+" }, /* U+2510 BOX DRAWINGS LIGHT DOWN AND LEFT [1.1] */
	{ 'x', "\xe2\x94\x82", "|" } /* U+2502 BOX DRAWINGS LIGHT VERTICAL [1.1] */
};

static void color2rgb(int color, int *red, int *green, int *blue) {
	if (color < 16) {
		int color_map[16][3] = {
			{ 0, 0, 0 }, { 205, 0, 0 }, { 0, 205, 0 }, { 205, 205, 0 }, { 0, 0, 238 },
			{ 205, 0, 205 }, { 0, 205, 205 }, { 229, 229, 229 }, { 127, 127, 127 },
			{ 255, 0, 0 }, { 0, 255, 0 }, { 255, 255, 0 }, { 92, 92, 255 }, { 255, 0, 255 },
			{ 0, 255, 255 }, { 255, 255, 255}
		};

		*red = color_map[color][0];
		*green = color_map[color][1];
		*blue = color_map[color][2];
	} else if (color < 232) {
		color -= 16;
		*red = color / 36;
		color -= 36 * *red;
		*red = *red == 0 ? 0 : 55 + 40 * *red;
		*green = color / 6;
		color -= 6 * *green;
		*green = *green == 0 ? 0 : 55 + 40 * *green;
		*blue = color;
		*blue = *blue == 0 ? 0 : 55 + 40 * *blue;
	} else if (color < 256) {
		color -= 232;
		*red = *green = *blue = color * 10 + 8;
	} else if (color == 256) {
		*red = *green = *blue = 0;
	} else if (color == 257) {
		*red = *green = *blue = 255;
	}
}

static void set_context_from_attr_idx(cairo_t *cr, PangoLayout *layout, PangoFontDescription *normal, PangoFontDescription *bold, attr_t attr) {
	int fg_color, bg_color;
	int r, g, b;

	if (attr & ATTR_BOLD) {
		pango_layout_set_font_description(layout, bold);
	} else {
		pango_layout_set_font_description(layout, normal);
	}

	fg_color = ((attr & ATTR_FG_MASK) >> ATTR_COLOR_SHIFT) - 1;
	bg_color = ((attr & ATTR_BG_MASK) >> (ATTR_COLOR_SHIFT + 9)) - 1;
	if (fg_color < 0)
		fg_color = 256;
	if (bg_color < 0)
		bg_color = 257;

	if (attr & ATTR_REVERSE) {
		int tmp;
		tmp = fg_color;
		fg_color = bg_color;
		bg_color = tmp;
	}

	color2rgb(bg_color, &r, &g, &b);
	cairo_set_source_rgb(cr, r, g, b);
	cairo_fill(cr);

	color2rgb(fg_color, &r, &g, &b);
	cairo_set_source_rgb(cr, r, g, b);
}

static void write_chars(cairo_t *cr, PangoLayout *layout, const char *str, size_t len) {
	size_t idx = 0, bytes;

	while (idx < len) {
		get_value(str + idx, &bytes);
		pango_layout_set_text(layout, str + idx, bytes);
		pango_cairo_show_layout(cr, layout);
		idx += bytes;
	}
}
#if 0
/* FIXME: finish drawing of the following attributes. */
/** Draw characters blinking. */
#define ATTR_BLINK ((attr_t) (1L << 4))
/** Draw characters with dim appearance. */
#define ATTR_DIM ((attr_t) (1L << 5))
/** Draw characters with stand-out. */
#define ATTR_STAND_OUT ((attr_t) (1L << 7))
#endif

static void write_single_image(window_t *win, int offset, cairo_t *cr, PangoLayout *layout,
		PangoFontDescription *font_description, PangoFontDescription *bold_font_description)
{
	int i, j;

	for (i = 0; i < win->height; i++) {
		int idx;
		for (j = 0, idx = 0; j < win->width && idx < win->lines[i].length; j++) {
			uint32_t block_size;
			attr_t attr;
			size_t bytes;
			td_bool fullwidth = td_false;

			block_size = get_value(win->lines[i].data + idx, &bytes);
			if (_BLOCK_SIZE_TO_WIDTH(block_size) == 2)
				fullwidth = td_true;

			cairo_rectangle(cr, j * cell_width + offset, i * cell_height, fullwidth ? cell_width * 2 : cell_width, cell_height);
			cairo_clip(cr);
			/* Set up path for fill. */
			cairo_rectangle(cr, j * cell_width + offset, i * cell_height, fullwidth ? cell_width * 2 : cell_width, cell_height);

			block_size >>= 1;
			idx += bytes;
			attr = get_attr(get_value(win->lines[i].data + idx, &bytes));
			idx += bytes;
			block_size -= bytes;
			set_context_from_attr_idx(cr, layout, font_description, bold_font_description, attr);
			if (!(attr & ATTR_INVISIBLE)) {
				cairo_move_to(cr, j * cell_width + offset, i * cell_height);
				if (attr & ATTR_ACS) {
					size_t k;
					for (k = 0; k < ARRAY_SIZE(acs_map); k++) {
						if (acs_map[k].idx == win->lines[i].data[idx]) {
							pango_layout_set_text(layout, acs_map[k].utf8, strlen(acs_map[k].utf8));
							if (pango_layout_get_unknown_glyphs_count(layout) > 0)
								pango_layout_set_text(layout, acs_map[k].alt, strlen(acs_map[k].alt));
							pango_cairo_show_layout(cr, layout);
							break;
						}
					}
				} else {
					write_chars(cr, layout, win->lines[i].data + idx, block_size);
				}
			}
			if (attr & ATTR_UNDERLINE) {
				cairo_move_to(cr, j * cell_width + 0.5 + offset, (i + 1) * cell_height - 0.5);
				cairo_line_to(cr, (j + 1) * cell_width - 0.5 + offset, (i + 1) * cell_height - 0.5);
				cairo_close_path(cr);
				cairo_set_line_width(cr, 1);
				cairo_stroke(cr);
			}
			idx += block_size;
			if (fullwidth)
				j++;
			cairo_reset_clip(cr);
		}
	}

	if (win->cursor_state != CURSOR_INVIS) {
		if (win->cursor_state == CURSOR_NORM) {
			cairo_rectangle(cr, win->paint_x * cell_width + 0.5 + offset, win->paint_y * cell_height + 0.5, cell_width - 1, cell_height - 1);
			cairo_set_line_width(cr, 1);
		} else {
			cairo_rectangle(cr, win->paint_x * cell_width + 1 + offset, win->paint_y * cell_height + 1, cell_width - 2, cell_height - 2);
			cairo_set_line_width(cr, 2);
		}
		cairo_set_operator(cr, CAIRO_OPERATOR_DIFFERENCE);
		cairo_set_source_rgb(cr, 255, 255, 255);
		cairo_stroke(cr);
		cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
	}
}

void win_write_image(window_t *winA, window_t *winB, const char *name) {
	cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		winA->width * cell_width + winB->width * cell_width + 4, MAX(winA->height, winB->height) * cell_height);
	cairo_t *cr = cairo_create(surface);

	cairo_surface_t *mask_surface = cairo_image_surface_create(CAIRO_FORMAT_A1, cell_width, cell_height);
	cairo_t *mask_cr = cairo_create(mask_surface);

	PangoLayout *layout;
	PangoFontDescription *font_description, *bold_font_description;

	cairo_set_source_rgba(mask_cr, 0, 0, 0, 1);
	cairo_paint(mask_cr);


	font_description = pango_font_description_new();
	pango_font_description_set_family(font_description, option_font);
	bold_font_description = pango_font_description_new();
	pango_font_description_set_absolute_size(font_description, cell_height * PANGO_SCALE * 0.75);
	pango_font_description_set_family(bold_font_description, option_font);
	pango_font_description_set_weight(bold_font_description, PANGO_WEIGHT_BOLD);
	pango_font_description_set_absolute_size(bold_font_description, cell_height * PANGO_SCALE * 0.75);

	layout = pango_cairo_create_layout(cr);
	pango_layout_set_font_description(layout, font_description);

	write_single_image(winA, 0, cr, layout, font_description, bold_font_description);
	write_single_image(winB, winA->width * cell_width + 4, cr, layout, font_description, bold_font_description);

	g_object_unref(layout);
	pango_font_description_free(font_description);

	cairo_destroy(cr);
	cairo_surface_write_to_png(surface, name);
	cairo_surface_destroy(surface);

	cairo_destroy(mask_cr);
	cairo_surface_destroy(mask_surface);
	return;
}
