#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "test-widget.h"

/* Init */
static void test_widget_class_init (TestWidgetClass *klass);
static void test_widget_init       (TestWidget *self);
static void test_widget_finalize   (GObject *object);


struct _TestWidget
{
    GtkWindow parent;

    gboolean entered;
	
};

G_DEFINE_TYPE (TestWidget, test_widget, GTK_TYPE_WINDOW)

static gboolean
test_widget_draw (GtkWidget *widget, cairo_t *cr)
{
    GtkStyleContext *context;
    TestWidget *self;
    GtkStateFlags state;
    gint radius = 0;
	
    self = TEST_WIDGET (widget);
	
    context = gtk_widget_get_style_context (widget);
	
    state = GTK_STATE_FLAG_NORMAL;
	
    /* If the widget is in entered state */
    if (self->entered) 
        state = GTK_STATE_FLAG_PRELIGHT;
	
    /* When state is GTK_STATE_FLAG_PRELIGHT: calling
     * gtk_style_context_get a storm of draw callbacks */
    gtk_style_context_get (context,
                           state,
                           "border-radius", &radius,
                           NULL);
	
    g_print ("draw event received\n");
	
    GTK_WIDGET_CLASS (test_widget_parent_class)->draw (widget, cr);

    return FALSE;
}

static gboolean 
test_widget_handle_enter_leave (GtkWidget *widget,
                               	GdkEventCrossing *evt)
{
    TestWidget *self;

    self = TEST_WIDGET(widget);
    printf ("EnterLeave Notify event \n");

    if(evt->type == GDK_ENTER_NOTIFY) 
    {
        self->entered = TRUE;
        gtk_widget_queue_draw (widget);
    }
    else if (evt->type == GDK_LEAVE_NOTIFY)
    {
        self->entered = FALSE;
        gtk_widget_queue_draw (widget);
    }
	
    return FALSE;
}

static void
test_widget_class_init (TestWidgetClass *klass)
{
    GObjectClass *object_class = G_OBJECT_CLASS (klass);
    GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);

    object_class->finalize = test_widget_finalize;
    
    widget_class->draw = test_widget_draw;
    widget_class->enter_notify_event = test_widget_handle_enter_leave;
    widget_class->leave_notify_event = test_widget_handle_enter_leave;
}

static void
test_widget_init (TestWidget *window)
{	
    gtk_widget_set_app_paintable(GTK_WIDGET(window), TRUE);
    gtk_window_set_default_size (GTK_WINDOW (window), 320, 200);
    gtk_container_set_border_width(GTK_CONTAINER(window), 0);
}

static void
test_widget_finalize (GObject *object)
{
    G_OBJECT_CLASS (test_widget_parent_class)->finalize (object);
}

GtkWidget *
test_widget_new (void)
{
    TestWidget *widget = NULL;
    widget = (TestWidget*)g_object_new (TEST_WIDGET_TYPE, NULL);
    return GTK_WIDGET (widget);
}
