#include <cairo.h>
#include <pango/pangocairo.h>
#include <gtk/gtk.h>
#include <stdlib.h>
#include <sqlite3.h>
#include <string.h>
#include <strings.h>
#include <libosso-abook/osso-abook.h>

#include "maenotify.h"


gint *
get_cell_radio_info(int w)
{
	GError *error;
	DBusGProxy *proxy;
	guchar cm,cl;
	gint *level, *mode;
	/*GdkPixbuf *level;
	GdkPixbuf *mode;
	*/
	mode=level=NULL;
	proxy = dbus_g_proxy_new_for_name (connection,"com.nokia.phone.net", "/com/nokia/phone/net", "Phone.Net");
	
	error = NULL;
	if ( w == 1 ) {
		/* radio mode */
		if (!dbus_g_proxy_call ( proxy, "get_radio_access_technology", &error, G_TYPE_INVALID,
					G_TYPE_UCHAR, &cm,
					G_TYPE_INT, NULL,
					G_TYPE_INVALID) )
		{
			g_object_unref (proxy);
			return NULL;
		} else {
			g_print("cm = %d\n",cm);
			/*if ( cm == 1 )
				mode = "/usr/share/icons/hicolor/scalable/hildon/statusarea_cell_mode_2g.png";
			else if ( cm == 2 ) 
				mode = "/usr/share/icons/hicolor/scalable/hildon/statusarea_cell_mode_3g.png";
			*/	
			g_object_unref (proxy);
			
			return (gint)cm;
		}
	} else if ( w == 2 ) {
		/* cell level */
		if (!dbus_g_proxy_call (proxy, "get_signal_strength", &error, G_TYPE_INVALID,
					G_TYPE_UCHAR, &cl,
					G_TYPE_UCHAR, NULL,
					G_TYPE_INT, NULL,
					G_TYPE_INVALID) ) 
		{
			g_object_unref (proxy);
			return NULL;
		} else {
			cl = cl + 20;
			cl = cl / 21;
			g_print("current level %d\n",cl);
			//5
			//level = g_strdup_printf("/usr/share/icons/hicolor/scalable/hildon/statusarea_cell_level%d.png",cl);
			
			g_object_unref (proxy);
			
			return (gint)cl;//level;
		}
	}
	
	g_object_unref (proxy);
	return NULL;				
}
gchar *
operator_name()
{
	GError *error;
	DBusGProxy *proxy;
	dbus_uint32_t op_code, country_code;
	gchar *name;
	
	proxy = dbus_g_proxy_new_for_name (connection,"com.nokia.phone.net", "/com/nokia/phone/net","Phone.Net");
	
	error = NULL;
	if (!dbus_g_proxy_call (proxy, "get_registration_status", &error, G_TYPE_INVALID,
  				G_TYPE_UCHAR, NULL,
  				G_TYPE_UINT, NULL,
  				G_TYPE_UINT, NULL,
				G_TYPE_UINT, &op_code,
				G_TYPE_UINT, &country_code,
				G_TYPE_UCHAR, NULL,
				G_TYPE_UCHAR, NULL,
				G_TYPE_INT, NULL,
				G_TYPE_INVALID) )
	{
		g_object_unref (proxy);
		return NULL;
	} else {
		error=NULL;
  
  		if (!dbus_g_proxy_call (proxy, "get_operator_name", &error, 
  				G_TYPE_UCHAR, 0,
  				G_TYPE_UINT, op_code,
  				G_TYPE_UINT, country_code,
  				G_TYPE_INVALID,
  				G_TYPE_STRING, &name,
  				G_TYPE_INT, NULL,
  				G_TYPE_INVALID) )
  		{
  			g_object_unref (proxy);
  			return NULL;
  		} else {
  			g_object_unref (proxy);
  			return name;
  		}
  	}
  	
  	g_object_unref (proxy);
  	return NULL;
	
}

GdkPixbuf *
fetch_avatar(gchar *uid)
{
	if ( ab_ready ){
		g_print("abook ready\n");
		GList *contacts;
		GList *l;
		OssoABookContact *contact;
		GdkPixbuf *pix;
		GdkPixbuf *out = NULL;
	    

		contacts = osso_abook_aggregator_lookup ( OSSO_ABOOK_AGGREGATOR (aggr), uid);
		if (contacts) {
			for (l = contacts; l; l = l->next) {
				contact = l->data;
				pix = osso_abook_contact_get_photo (contact);
				if ( pix != NULL )
					out = gdk_pixbuf_scale_simple (pix, 48,48, GDK_INTERP_BILINEAR);
	//			g_print ("215 ==> %s\n",
	//				osso_abook_contact_get_display_name (contact));
			}
		} else {
			g_print ("No contacts found with phone number\n");
		}

		g_list_free (contacts);
	
		return out;
	} else return NULL;
}

void
get_counters(long st, long et)
{
	g_print("get counters\n");
	
	//int rc;
	sqlite3_stmt *res_stmt = NULL;
	gchar *ret;
	ret = NULL;
	int ac = 0;

	

	if ( SQLITE_OK == sqlite3_prepare(db, g_strdup_printf("select remote_name, E.remote_uid, datetime(start_time,'unixepoch') start_time, R.abook_uid from Events as E, EventTypes ET, Remotes as R where E.event_type_id=3 and E.is_read=0 and R.remote_uid=E.remote_uid and E.local_uid=R.local_uid and E.start_time between %ld and %ld order by start_time desc limit 3",st,et),-1, &res_stmt, NULL) ) {
	       	while ( SQLITE_ROW == sqlite3_step(res_stmt) ) {
			ret = g_strdup_printf("%s@<b>%s</b>\n<span size=\"xx-small\">%s</span>\n",ret,( sqlite3_column_text(res_stmt, 0) != NULL ) ? sqlite3_column_text(res_stmt, 0) : sqlite3_column_text(res_stmt, 1),sqlite3_column_text(res_stmt, 2));
			cavatars[ac] = fetch_avatar(sqlite3_column_text(res_stmt, 3));
			ac++;
		}
		calls_count = g_strdup(ret);
	}  else {
		g_print("query fails\n");
		calls_count = NULL;
	}
	ret = NULL;
	ac = 0;
	if ( SQLITE_OK == sqlite3_prepare(db, g_strdup_printf("select remote_name, E.remote_uid, datetime(start_time,'unixepoch') start_time, R.abook_uid from Events as E, EventTypes ET, Remotes as R where E.event_type_id=7 and E.is_read=0 and R.remote_uid=E.remote_uid and E.local_uid=R.local_uid and E.start_time between %ld and %ld order by start_time desc limit 3",st,et),-1, &res_stmt, NULL) ) {
	       	while ( SQLITE_ROW == sqlite3_step(res_stmt) ) {
			ret = g_strdup_printf("%s@<b>%s</b>\n<span size=\"xx-small\">%s</span>\n",ret,( sqlite3_column_text(res_stmt, 0) != NULL ) ? sqlite3_column_text(res_stmt, 0) : sqlite3_column_text(res_stmt, 1),sqlite3_column_text(res_stmt, 2));
			savatars[ac] = fetch_avatar(sqlite3_column_text(res_stmt, 3));
			ac++;
		}
		sms_count = g_strdup(ret);
	}  else {
		g_print("query fails\n");
		sms_count = NULL;
	}
	ret = NULL;
	
	sqlite3_finalize(res_stmt);
	
}

long
get_timestamp(int w)
{
	time_t t;
	struct tm *timeinfo;
	time(&t);
	timeinfo = localtime(&t);
	
	if ( w == 0 ) { //start time
		timeinfo->tm_hour = 00;
		timeinfo->tm_min = 00;
		timeinfo->tm_sec = 00;
	} else { //end time
		timeinfo->tm_hour = 23;
		timeinfo->tm_min = 59;
		timeinfo->tm_sec = 59;
	}

	return (long)mktime(timeinfo);
}
		    
		    
	

void
restore_info()
{
	g_print("restoring...\n");
	current_lock = FALSE;
	//wrong way
	system("cp /home/user/.maenotify/lockslider.png /etc/hildon/theme/backgrounds/lockslider.png");
}


gboolean
update_info( gpointer data )
{
	g_print("in update_info() *** \n");
	cairo_surface_t *base;
	cairo_t         *cr;
	cairo_status_t  result;
	gint		bat_level;
	
	
	
	base = cairo_image_surface_create_from_png ( "/home/user/.maenotify/lockslider.png" );
	cr = cairo_create (base);
//	cairo_move_to (cr, 10.0, 10.0);

//	cairo_move_to(cr, 10.0,25.0);
	
//	cairo_show_text ( cr, "per sbloccare");//g_strdup_printf("%d%",bat_level) );
	
	/* BATTERY PERCENTAGE */
	bat_level = libhal_device_get_property_int( ctx, BATTERY_DEV, BATTERY_PERCENTAGE, NULL );
	g_print("bat level =%d\n",bat_level);
	
	cairo_set_source_rgb(cr, 1,1,1);
	cairo_rectangle ( cr, 8.5,5.0, 8, 4 );
	cairo_fill(cr);
	cairo_stroke (cr);
  
	cairo_rectangle ( cr, 5.0,8.5, 16, 36.0 ); 
	cairo_stroke (cr);

	cairo_save(cr);
	   

	cairo_set_source_rgb(cr, 0.4, 0.6, 0.2);//163,19);
	cairo_rectangle ( cr, 6.0,38.0/*30*/, 14, 5.0/*14.0*/);//6 );
	//			    --      ++
	cairo_fill(cr);
	cairo_stroke (cr);

	cairo_set_source_rgb (cr, 139,137,137);
	

	cairo_move_to ( cr, 1.5, 60 );
	cairo_select_font_face (cr, "Times", CAIRO_FONT_SLANT_NORMAL,CAIRO_FONT_WEIGHT_BOLD);
	cairo_set_font_size (cr, 18.0);
/*	layout = pango_cairo_create_layout (cr);
	pango_layout_set_font_description (layout, desc);
	pango_layout_set_markup (layout, g_strdup_printf("<b>%d%</b>",bat_level), -1);*/
	cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
//	pango_cairo_show_layout (cr, layout);	
	gchar *bl;
	bl = g_strdup_printf("%d",bat_level);
	bl = g_strconcat(bl,"%",NULL);
	cairo_show_text (cr, bl);//g_strdup_printf("%d",bat_level));
	g_free(bl);
	/*
	cairo_move_to(cr,15,20);
	cairo_set_source_rgb(cr,1,1,1);
	cairo_show_text ( cr, "per sbloccare");//g_strdup_printf("%d%",bat_level) );
  */
  	cairo_stroke(cr);
	cairo_save(cr);
	
	/* CELLULAR SIGNAL LEVEL */
	int i;
	int cl = get_cell_radio_info(2);
	for ( i=0;i<cl;i++ )
		cairo_rectangle ( cr, 780/*30*/, 10+(i*5), 16,3 );

	cairo_fill(cr);
	cairo_stroke(cr);

	cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
	cairo_move_to (cr, 775.0, 10+(i*4)+18);	
	if ( get_cell_radio_info(1) == 1 )
		cairo_show_text(cr, "2G");
	else cairo_show_text(cr, "3G");
	
	  
	  /*
	cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL,CAIRO_FONT_WEIGHT_BOLD);
	cairo_set_font_size (cr, 22.0);
	
	if ( get_cell_radio_info(1) == 1 )
		cairo_show_text (cr, "2G");
	else cairo_show_text (cr, "3G");
*/
	cairo_stroke(cr);
	cairo_save (cr);
	
/*
	gdk_cairo_set_source_pixbuf(cr,gdk_pixbuf_new_from_file ( "/usr/share/icons/hicolor/scalable/hildon/statusarea_battery_full63.png", NULL ), 25.0, 5.0);
        cairo_paint_with_alpha (cr, 0.0);
        cairo_paint(cr);
		
/*
	cairo_t *cr_bat,*cr_opname,*cr_cellevel,*cr_call,*cr_sms;
	
	cr_bat = cairo_image_surface_create_from_png ( "/usr/share/icons/hicolor/scalable/hildon/statusarea_battery_full63.png" );
	
	
	cr_opname = cairo_image_surface_create_from_png ( get_cell_radio_info(1) );
	cr_cellevel = cairo_image_surface_create_from_png ( get_cell_radio_info(2) );

	
	pango_font_description_set_weight (desc, PANGO_WEIGHT_BOLD);
	pango_font_description_set_absolute_size (desc, 20 * PANGO_SCALE);
	
//	cairo_paint(cr);
	
	layout = pango_cairo_create_layout (cr);
	pango_layout_set_font_description (layout, desc);
	
	pango_layout_set_markup (layout, g_strdup_printf("<b>%d%</b>",bat_level), -1);
	cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
	cairo_move_to (cr, 30.0, 20.0);
	//180 * RADIANTI / PI
//	cairo_rotate (cr, G_PI * 90 / 180 );
	pango_cairo_show_layout (cr, layout);
	*/
	/* draw operator name at dx */

	
	gchar *op_name;
	op_name = g_strdup(operator_name());
	
	//pango_layout_set_markup (layout, g_strdup_printf("<b>%s</b>",op_name), -1);
	cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
	
	//g_print("%s len =%d\n",op_name,g_utf8_strlen(op_name,-1));
	cairo_move_to (cr, (800.0-(g_utf8_strlen(op_name,-1)*10)-30), 24.0);
	cairo_show_text (cr, op_name);
	//pango_cairo_show_layout (cr, layout);
	cairo_stroke(cr);
	cairo_save(cr);
	
	/*
	cairo_move_to(cr, 650,20.0);
	cairo_select_font_face (cr, "Times", CAIRO_FONT_SLANT_NORMAL,CAIRO_FONT_WEIGHT_BOLD);
	cairo_set_font_size (cr, 18.0);
	cairo_set_source_rgb(cr,1,1,1);
	cairo_show_text(cr, "vodafone");
	cairo_stroke(cr);
	cairo_save(cr);
	/**/

	
	
	
	if ( /*g_strcmp0(current_lock,"locked") == 0 || (*/ sms_count != NULL || calls_count != NULL /*)*/ ) {
	
	pango_font_description_set_weight (desc, PANGO_WEIGHT_BOLD);
	pango_font_description_set_absolute_size (desc, 22 * PANGO_SCALE);

	//base = cairo_image_surface_create_from_png ( "/home/user/.maenotify/lockslider.png" ); //"/usr/share/themes/alpha/backgrounds/lockslider.png" );

	//cr = cairo_create (base);
	cairo_move_to (cr, 10.0, 10.0);

	
	

	int bottom=430;
	

	if ( calls_count != NULL ) {
		gchar **c;
		
		c = g_strsplit(calls_count,"@",-1);
		int i;
		for (i=1; c[i] ;i++)
		{
			if ( cavatars[i-1] == NULL )
				gdk_cairo_set_source_pixbuf(cr,cpixbuf, 5.0, bottom);
			else
				gdk_cairo_set_source_pixbuf(cr,cavatars[i-1], 5.0, bottom);
				
//			cairo_paint_with_alpha (cr, 0.0);
			cairo_paint(cr);
			pango_layout_set_markup (layout, c[i], -1);
			cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
			cairo_move_to (cr, 55.0, bottom);
			bottom=bottom-50;
			pango_cairo_show_layout (cr, layout);
		}
		g_strfreev (c);
	}

	pango_layout_set_justify ( layout, TRUE );
	pango_layout_set_alignment ( layout, PANGO_ALIGN_RIGHT );

	bottom=430;
	if ( sms_count != NULL ) {
	
		gchar **s;
		
		s = g_strsplit(sms_count,"@",-1);
		int i;
		for (i=1; s[i] ;i++)
		{
			if ( savatars[i-1] == NULL )
				gdk_cairo_set_source_pixbuf(cr,spixbuf, 750.0, bottom);
			else
				gdk_cairo_set_source_pixbuf(cr,savatars[i-1], 750.0, bottom);
				
//			gdk_cairo_set_source_pixbuf(cr,spixbuf, 750.0, bottom);
//			cairo_paint_with_alpha (cr, 0.0);
			cairo_paint(cr);
			pango_layout_set_markup (layout, s[i], -1);
			cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
			cairo_move_to (cr, 600, bottom);
			bottom=bottom-50;
			pango_cairo_show_layout (cr, layout);
		}
		g_strfreev (s);
	}
	}


	cairo_stroke_preserve(cr);
	result = cairo_surface_write_to_png (base, "/etc/hildon/theme/backgrounds/lockslider.png");
	
	if ( result == CAIRO_STATUS_SUCCESS ) {
		
		g_print("result ok\n");

	} else {
		g_print("result fails\n");
		return FALSE;
    	}
	g_object_unref(layout);
	cairo_surface_destroy(base);
	cairo_destroy(cr);
	
	return TRUE;
   //} else system("cp /home/user/.maenotify/lockslider.png /etc/hildon/theme/backgrounds/lockslider.png");
	
}
