#include <error-mem-viewer/err-mem-viewer-hex-cell-renderer.h>
#include <string.h>

struct _ErrMemViewHexCellRenderer {
	GtkCellRendererText base;
};

enum {
	PROP_HEXNUM = 1,
	PROP_COUNT
};

G_DEFINE_TYPE(ErrMemViewHexCellRenderer, err_mem_view_address_cell_renderer, GTK_TYPE_CELL_RENDERER_TEXT)

static void err_mem_view_address_cell_renderer_init(ErrMemViewHexCellRenderer *self)
{
	(void)self;
}

static void convert_gvalue_uint_to_string(const GValue *in, GValue *out)
{
	uint32_t val;
	char text[32];

	if (!in || !out)
		return;

	g_value_init(out, G_TYPE_STRING);

	val = g_value_get_uint(in);
	snprintf(text, sizeof(text), "0x%08X", val);
	g_value_set_string(out, text);
}

static void err_mem_view_address_cell_renderer_set_property(GObject *obj, guint param_id, const GValue *value, GParamSpec *pspec)
{
	GValue val = G_VALUE_INIT;

	switch (param_id) {
	case PROP_HEXNUM:
		convert_gvalue_uint_to_string(value, &val);
		g_object_set_property(obj, "text", &val);
		g_value_unset(&val);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void err_mem_view_address_cell_renderer_get_property(GObject      *object,
							    guint        param_id,
							    GValue	*value,
							    GParamSpec   *pspec)
{
	(void)value;

	switch (param_id) {
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(object, param_id, pspec);
		break;
	}
}

static GParamSpec *properties[PROP_COUNT];

void err_mem_view_address_cell_renderer_class_init(ErrMemViewHexCellRendererClass *klass)
{
	GObjectClass *oclass = G_OBJECT_CLASS(klass);

	oclass->set_property = err_mem_view_address_cell_renderer_set_property;
	oclass->get_property = err_mem_view_address_cell_renderer_get_property;

	properties[PROP_HEXNUM] = g_param_spec_uint("hex-num", "hex-num", "Hex number to display", 0U, UINT_MAX, 0U, G_PARAM_WRITABLE);
	g_object_class_install_properties(oclass, PROP_COUNT, properties);
}

GtkCellRenderer *err_mem_view_hex_cell_renderer_new()
{
	return GTK_CELL_RENDERER(g_object_new(ERR_MEM_VIEW_TYPE_HEX_CELL_RENDERER, NULL));
}
