/* mail plugin for ipbox9000/cuberevo */
/* 18.07.08 by kneubi                   */
/* ipbox@kneubis.ch                     */

#define _GNU_SOURCE

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <mailutils/mailutils.h>


/* modules header */
#include "plugin/plugin.h"
#include "fb/gtools.h"
#include "fb/image.h"
#include "event/event.h"
#include "font/font.h"
#include "ui/wm.h"
#include "jpeg/inf.h"

/* sbox header */
#include "directory.h"

/* plugin header (./include) */
#include "mailplg.h"

plugin_info( author,    "Kneubi" );
plugin_info( rev,       "0.0.1" );
plugin_info( desc,      "mail plugin" );
plugin_info( ldesc,     "show mails from pop3/imap server" );

/* define rc states */
#define RC_ACCOUNT 0
#define RC_HEADER  1
#define RC_MESSAGE 2
#define RC_ERROR   5

/* variables */
char *cfgfile="mail-plugin.cfg";
img_t bgimg;
int rc_state;
static window_t *window = NULL;
extern int errno;
int errorstate=0;

#ifdef DEBUG
  FILE *dbgfilefh;
  char *dbgfile="/tmp/mailplg-debug.txt";
  char *dbgtext;
#endif


/* define structure to hold mail accounts */
static struct mail_accounts {
   int focus;
   int start_focus;
   int nr_accounts;
   char **descr;
   char **url;
} m_accounts;

/* define structure to hold mailbox */
static struct mail_mailbox {
   int focus;
   int start_focus;
   int nr_messages;
   mu_mailbox_t mbox;
   char *mailboxurl;
   size_t msgno;
   size_t total;
   char **header_summary;
} m_mailbox;

/* define structure to hold message */
static struct mail_message {
   int focus;
   int start_focus;
   char **message;
   int lines;
} m_message;

/* Prototypes */
static void mailplg_wm_init();
static void mailplg_config_parser();
static void mailplg_account_update();
static void mailplg_get_messages();
static void mailplg_disp_header();
static void mailplg_disp_message();
static int mailplg_event_handler(event_t *event);
static void mailplg_error_handler(char *errdescr,const char *errstring);
static void mailplg_cleanup(void);

#ifdef DEBUG
  static void mailplg_debug_handler(char *debugtext);
#endif


/* main func. */

int plugin_main(int argc, char *argv[])
{
	/* open debugfile if necessary */
	#ifdef DEBUG
	  dbgfilefh=fopen(dbgfile,"w");
	#endif

        /* initialize event module (for REMOTE )*/
        plug_event_init();

	mailplg_wm_init();
	mailplg_config_parser(); 
	mailplg_account_update();

        /*
         *      handling remote key event
         */

        while(1)
        {
                event_t event;

                if( plug_event_rcv( &event ) < 0 )
                        continue;

                /* in plugin only event_type_key is valid */
                if( event.type != event_type_key)
                        continue;

                if( mailplg_event_handler(&event) < 0)
                        break;
        }

        mailplg_cleanup();

	/* close  debugfile if necessary */
	#ifdef DEBUG
	  fclose(dbgfilefh);
	#endif

        return 0;
} 

static void mailplg_wm_init()
{
	#ifdef DEBUG
	  asprintf(&dbgtext,"entering mailplg_wm_init function");
	  mailplg_debug_handler(dbgtext);
	  free(dbgtext);
	#endif
	/* variables */
	char *fullpath;
	struct stat sbgimg;

	/* check for background */
        asprintf(&fullpath,"%s/bg-mailplg.jpg",dir_plugin);
        stat(fullpath,&sbgimg);
        if((S_ISREG(sbgimg.st_mode))) {
          #ifdef DEBUG
	    asprintf(&dbgtext,"using %s/bg-mailplg.jpg as background",dir_plugin);
	    mailplg_debug_handler(dbgtext);
	    free(dbgtext);
	  #endif

          if(JPEG_convert_to_BMP_plugin(fullpath)) {
            bgimg = img_open_absolute_path(plug_bgbmp);
          #ifdef DEBUG
            asprintf(&dbgtext,"successfully converted %s/bg-mailplg.jpg to bmp",dir_plugin);
            mailplg_debug_handler(dbgtext);
            free(dbgtext);
          #endif
          }
        }  else {
           bgimg = NULL;
	}

        free(fullpath);

        rect_t rect = { 0, 0, 720, 576 };

        /* create FB_WINDOW */
        window = wm_create(
                        &rect,            /* coordinate */
                        "mail plugin",  /* name of window */
                        NULL,             /* redraw callback */
                        NULL,             /* parent window */
                        COLOR_TRANSPARENT /* color key for TRANSPARENT */
                        );

         #ifdef DEBUG
           asprintf(&dbgtext,"leaving mailplg_wm_init_function\n");
           mailplg_debug_handler(dbgtext);
           free(dbgtext);
         #endif

}

static void mailplg_config_parser()
{
  #ifdef DEBUG
    asprintf(&dbgtext,"entering mailplg_config_parser function");
    mailplg_debug_handler(dbgtext);
    free(dbgtext);
  #endif

   /* check if we had a error */
 if ( errorstate == 0) {
 
  char *fullpath;
  FILE *cfgfileptr;
  char *buffer=NULL,*tmpdescr=NULL,*tmpurl=NULL;
  size_t len = 0;
  size_t rchars = 0;
  int counter;

  /* initialize structs */
  memset(&m_accounts,0, sizeof(m_accounts));
  memset(&m_mailbox,0, sizeof(m_mailbox));

  /* create fullpath to configfile */
  asprintf(&fullpath,"%s/%s",dir_plugin,cfgfile);
 
    /* parse config file */
  cfgfileptr=fopen(fullpath,"r");
  if  (cfgfileptr == NULL) {
    #ifdef DEBUG
      asprintf(&dbgtext,"unable to open %s",fullpath);
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif

    mailplg_error_handler("unable to open mail-plugin.cfg",strerror(errno));
  } else {

    #ifdef DEBUG
      asprintf(&dbgtext,"successfully opened %s",fullpath);
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif

    while((rchars=getline(&buffer,&len,cfgfileptr)) != -1) {
       /* skip comments and empty lines*/
       if ( buffer[0] != 35 && rchars > 1 ) {
        /* split line in description and url */
        tmpdescr=strtok(buffer,":") ;
	tmpurl=strtok(NULL,"\n");

        /* increment mailbox counter if we have url and desc*/
	if (tmpdescr != NULL && tmpurl != NULL) {
          /* remove dos carriage return */
          counter=0;
          while (counter <= strlen(tmpurl)) {
            if (tmpurl[counter] == '\r') {
              tmpurl[counter]= '\0';
              #ifdef DEBUG
                asprintf(&dbgtext,"removing dos carriage return from: %s",tmpurl);
                mailplg_debug_handler(dbgtext);
                free(dbgtext);
              #endif
            }
            counter++;
          }
          m_accounts.nr_accounts++;
          #ifdef DEBUG
            asprintf(&dbgtext,"incrementing m_accounts.nr_accounts to %i",m_accounts.nr_accounts);
            mailplg_debug_handler(dbgtext);
            free(dbgtext);
          #endif
	  /* store values in array */
          #ifdef DEBUG
            asprintf(&dbgtext,"adding %s:%s to m_accounts array",tmpdescr,tmpurl);
            mailplg_debug_handler(dbgtext);
            free(dbgtext);
          #endif
          /* allocate memory for char pointers*/
          m_accounts.descr=realloc(m_accounts.descr,(sizeof(char *) * m_accounts.nr_accounts));
          m_accounts.url=realloc(m_accounts.url, (sizeof(char *) * m_accounts.nr_accounts ));
	  /* copy description to array */
          m_accounts.descr[m_accounts.nr_accounts -1 ]=malloc(strlen(tmpdescr)+1) ;
          strcpy(m_accounts.descr[m_accounts.nr_accounts -1 ],tmpdescr) ;
	  /* copy url to array */
          m_accounts.url[m_accounts.nr_accounts -1 ]=malloc(strlen(tmpurl)+1);
          strcpy(m_accounts.url[m_accounts.nr_accounts -1 ],tmpurl);
	}
        /* reset buffer */
       buffer=NULL;
      }
    }
    /* cleanup */
    fclose(cfgfileptr);
    #ifdef DEBUG
      asprintf(&dbgtext,"freeing buffer");
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif
    if (buffer) 
      free(buffer);
    free (fullpath);
  }
 }
 #ifdef DEBUG
   asprintf(&dbgtext,"leaving mailplg_config_parser function\n");
   mailplg_debug_handler(dbgtext);
   free(dbgtext);
 #endif

}

	         
static void mailplg_account_update()
{
    #ifdef DEBUG
      asprintf(&dbgtext,"entering mailplg_account_update function");
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif
    /* check if we had a error */
    if ( errorstate == 0)  {
	/* check if we have accounts */
	if ( m_accounts.nr_accounts == 0 ) {
    		#ifdef DEBUG
      		  asprintf(&dbgtext,"no accounts defined in %s",cfgfile);
      		  mailplg_debug_handler(dbgtext);
      		  free(dbgtext);
    		#endif
    		mailplg_error_handler("no accounts defined in",cfgfile);
		return;
	}
	/* set rc_state */
        rc_state=RC_ACCOUNT;

	char *footer="OK: select    EXIT: quit     PUP/PDOWN: next screen   UP/DOWN: up/down";
	struct _font font = { .size = 18 };

  	/* draw background */ 
        if(bgimg)
                img_draw(&window->fb,bgimg,window->gc, 0,0,720,576,
                                IMG_ALIGN_CENTER|IMG_ALIGN_MIDDLE);
        else
        {
                gc_set_fc(window->gc,0x00c3c4c5); /* foreground color */
                gc_set_bc(window->gc,0x00c3c4c5); /* foreground color */
                gt_fillrect(&window->fb,window->gc, 0,0,720,576);
        }

        if(m_accounts.focus >= m_accounts.nr_accounts  || m_accounts.focus < 0)
                return;

        gc_set_fc(window->gc,0x00ffffff); /* foreground color */
        gc_set_bc(window->gc,0x00ff00ff); /* background color */

        gc_set_lt(window->gc,2); /* thickness of line */

        /* draw focusing box */
        // rectangle , if you want draw a filled rectable, use gt_fillrect() */
        gt_rect(&window->fb,window->gc,
                        MENU_X,MENU_Y+(m_accounts.focus-m_accounts.start_focus)*MENU_H,MENU_W,MENU_H);

        /* draw contents */
        int i;
        for( i = 0; (i < MAX_LINE_NUM) && (i + m_accounts.start_focus < m_accounts.nr_accounts); i++)
        {
                #ifdef DEBUG
                  asprintf(&dbgtext,"adding %s to focusing box",m_accounts.descr[i+m_accounts.start_focus]);
                  mailplg_debug_handler(dbgtext);
                  free(dbgtext);
                #endif

                font_draw_str(
                                &font,m_accounts.descr[i+m_accounts.start_focus],strlen(m_accounts.descr[i+m_accounts.start_focus]),
                                &window->fb,window->gc,
                                MENU_ITEM_X,MENU_ITEM_Y + i * MENU_ITEM_H);
        }
	
	/* print footer */
        font_draw_str(
                     &font,footer,strlen(footer),
                                &window->fb,window->gc,
                                MENU_ITEM_X,510);

        wm_redraw(window);
        wm_show(window);
 
   }
    #ifdef DEBUG
      asprintf(&dbgtext,"leaving mailplg_account_update function\n");
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif
}

static void mailplg_disp_header()
{
    #ifdef DEBUG
      asprintf(&dbgtext,"entering mailplg_disp_header function");
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif
    /* check if we had a error */
    if ( errorstate == 0)  {

	struct _font font = { .size = 18 };
	char *footer="OK: select  EXIT: quit   MENU: back    PUP/PDOWN: screen+/-   UP/DOWN: +/-";
	char *nomessages="no messages";

  	/* draw background */ 
        if(bgimg)
                img_draw(&window->fb,bgimg,window->gc, 0,0,720,576,
                                IMG_ALIGN_CENTER|IMG_ALIGN_MIDDLE);
        else
        {
                gc_set_fc(window->gc,0x00c3c4c5); /* foreground color */
                gc_set_bc(window->gc,0x00c3c4c5); /* foreground color */
                gt_fillrect(&window->fb,window->gc, 0,0,720,576);
        }

        gc_set_fc(window->gc,0x00ffffff); /* foreground color */
        gc_set_bc(window->gc,0x00ff00ff); /* background color */

        gc_set_lt(window->gc,2); /* thickness of line */

        /* draw focusing box */

        // rectangle , if you want draw a filled rectable, use gt_fillrect() */
        gt_rect(&window->fb,window->gc,
                        MENU_X,MENU_Y+(m_mailbox.focus-m_mailbox.start_focus)*MENU_H,MENU_W,MENU_H);


        /* draw contents */
        if ( m_mailbox.total > 0 ) {
	  int i;
          for( i = 0; (i < MAX_LINE_NUM) && (i + m_mailbox.start_focus < m_mailbox.total  ); i++)
          {
            #ifdef DEBUG
              asprintf(&dbgtext,"adding %s to focusing box",m_mailbox.header_summary[i+m_mailbox.start_focus]);
              mailplg_debug_handler(dbgtext);
              free(dbgtext);
            #endif
                  font_draw_str(
                                &font,m_mailbox.header_summary[i+m_mailbox.start_focus],strlen(m_mailbox.header_summary[i+m_mailbox.start_focus]),
                                &window->fb,window->gc,
                                MENU_ITEM_X,MENU_ITEM_Y + i * MENU_ITEM_H);
          }
	} else {
            #ifdef DEBUG
              asprintf(&dbgtext,"no messages");
              mailplg_debug_handler(dbgtext);
              free(dbgtext);
            #endif
          font_draw_str(
            &font,nomessages,strlen(nomessages),&window->fb,window->gc,
            MENU_ITEM_X,MENU_ITEM_Y);
        }


	/* print footer */
        font_draw_str(
                     &font,footer,strlen(footer),
                                &window->fb,window->gc,
                                MENU_ITEM_X - 15 ,510);

        wm_redraw(window);
        wm_show(window);
 
   }
    #ifdef DEBUG
      asprintf(&dbgtext,"leaving mailplg_disp_header function\n");
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif
}

static void mailplg_disp_message()
{
    #ifdef DEBUG
      asprintf(&dbgtext,"entering mailplg_disp_message function");
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif
    /* check if we had a error */
    if ( errorstate == 0)  {
        /* init struct */
        memset(&m_message,0, sizeof(m_message));
	m_message.lines=3;
	int status;
        char *charset = "utf-8";
	char *footer="EXIT: quit     MENU: back      PUP/PDOWN: screen+/-";

	/*create output */
        mu_message_t msg;
        mu_header_t hdr;
	char *from, *subject, *date;
	char *subjectutf,*fromutf;

        #ifdef DEBUG
          asprintf(&dbgtext,"display message nr: %i",m_mailbox.focus + 1);
          mailplg_debug_handler(dbgtext);
          free(dbgtext);
        #endif

        if ((status = mu_mailbox_get_message (m_mailbox.mbox, (m_mailbox.focus + 1), &msg)) != 0
             || (status = mu_message_get_header (msg, &hdr)) != 0)
        {
	  #ifdef DEBUG
            asprintf(&dbgtext,"Error: %s",mu_strerror (status));
            mailplg_debug_handler(dbgtext);
            free(dbgtext);
          #endif
          mailplg_error_handler("Error",mu_strerror (status)); 
	  return;

        }
        /* extract sender from header */
        if (mu_header_aget_value (hdr, MU_HEADER_FROM, &from)) 
           from = strdup ("(NO FROM)");
        /* extract subject from header */
        if (mu_header_aget_value (hdr, MU_HEADER_SUBJECT, &subject))
           subject = strdup ("(NO SUBJECT)");
        /* extract send time from header */
        if (mu_header_aget_value (hdr, MU_HEADER_DATE, &date))
           subject = strdup ("(NO DATE)");

         /* convert subject and sender to local charset*/
         mu_rfc2047_decode(charset,subject,&subjectutf);
         mu_rfc2047_decode(charset,from,&fromutf);

	 /* alloc space for headers */
	 m_message.message=realloc(m_message.message,(sizeof(char *) * m_message.lines));

	 /* copy header to array */
	 asprintf(&m_message.message[0],"From:     %s",fromutf);
	 asprintf(&m_message.message[1],"Subject: %s",subjectutf);
	 asprintf(&m_message.message[2],"Date:      %s",date);

	struct _font font = { .size = 18 };

  	/* draw background */ 
        if(bgimg)
                img_draw(&window->fb,bgimg,window->gc, 0,0,720,576,
                                IMG_ALIGN_CENTER|IMG_ALIGN_MIDDLE);
        else
        {
                gc_set_fc(window->gc,0x00c3c4c5); /* foreground color */
                gc_set_bc(window->gc,0x00c3c4c5); /* foreground color */
                gt_fillrect(&window->fb,window->gc, 0,0,720,576);
        }


        gc_set_fc(window->gc,0x00ffffff); /* foreground color */
        gc_set_bc(window->gc,0x00ff00ff); /* background color */

//        gc_set_lt(window->gc,2); /* thickness of line */


        /* draw contents */
        int i;
        for( i = 0; (i < MAX_LINE_NUM) && (i + m_message.start_focus < m_message.lines  ); i++)
        {
          #ifdef DEBUG
            asprintf(&dbgtext,"adding line  %s to output array",m_message.message[i+m_message.start_focus]);
            mailplg_debug_handler(dbgtext);
            free(dbgtext);
          #endif

                font_draw_str(
                                &font,m_message.message[i+m_message.start_focus],strlen(m_message.message[i+m_message.start_focus]),
                                &window->fb,window->gc,
                                MENU_ITEM_X,MENU_ITEM_Y + i * MENU_ITEM_H);
        }

	/* print footer */
        font_draw_str(
                     &font,footer,strlen(footer),
                                &window->fb,window->gc,
                                MENU_ITEM_X,510);

        wm_redraw(window);
        wm_show(window);

	/* cleanup */
        #ifdef DEBUG
          asprintf(&dbgtext,"freeing from,subject and date");
          mailplg_debug_handler(dbgtext);
          free(dbgtext);
        #endif
	free (from);
	free (subject);
	free (date);

	for (i = 0; ( i < m_message.lines); i++)
	{
          #ifdef DEBUG
            asprintf(&dbgtext,"freeing %s",m_message.message[i]);
            mailplg_debug_handler(dbgtext);
            free(dbgtext);
          #endif
	  free(m_message.message[i]);
	} 
        #ifdef DEBUG
          asprintf(&dbgtext,"freeing m_message.message");
          mailplg_debug_handler(dbgtext);
          free(dbgtext);
        #endif
	free (m_message.message);
   }
    #ifdef DEBUG
      asprintf(&dbgtext,"leaving mailplg_disp_message function\n");
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif
}

static void mailplg_get_messages()
{
    #ifdef DEBUG
      asprintf(&dbgtext,"entering mailplg_get_messages function");
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif
    /* check if we had a error */
    if ( errorstate == 0)  {

       char *from=NULL,*subject=NULL,*date=NULL;
       int status;
       struct tm mailtime;
       char shorttime[25];
       char *subjectutf=NULL,*fromutf;
       char *charset = "utf-8";

       /* Register the formats. */
       #ifdef DEBUG
         asprintf(&dbgtext,"registering all mbox formats");
         mailplg_debug_handler(dbgtext);
         free(dbgtext);
       #endif
       mu_register_all_mbox_formats ();

       /* create mailbox object */
       #ifdef DEBUG
         asprintf(&dbgtext,"create mailbox object");
         mailplg_debug_handler(dbgtext);
         free(dbgtext);
       #endif
       status = mu_mailbox_create_default (&m_mailbox.mbox, m_mailbox.mailboxurl);
       if (status != 0) {
           #ifdef DEBUG
             asprintf(&dbgtext,"unable to create mbox: %s",mu_strerror (status));
             mailplg_debug_handler(dbgtext);
             free(dbgtext);
           #endif
           mailplg_error_handler("unable to create mbox", mu_strerror (status));
	   return;
	   }

       /* open connection */
       if (m_mailbox.mbox) {
         #ifdef DEBUG
           asprintf(&dbgtext,"open mailbox connection");
           mailplg_debug_handler(dbgtext);
           free(dbgtext);
         #endif
         status = mu_mailbox_open (m_mailbox.mbox, MU_STREAM_READ);
         if (status != 0) {
           #ifdef DEBUG
             asprintf(&dbgtext,"unable to open mbox: %s",mu_strerror (status));
             mailplg_debug_handler(dbgtext);
             free(dbgtext);
           #endif
           mailplg_error_handler("unable to open mbox",mu_strerror (status));
	   return;
         }

         /* count messages */
         mu_mailbox_messages_count (m_mailbox.mbox, &m_mailbox.total);
         #ifdef DEBUG
           asprintf(&dbgtext,"mailbox has %i messages",m_mailbox.total);
           mailplg_debug_handler(dbgtext);
           free(dbgtext);
         #endif

         /* allocate memory for char pointers*/
         #ifdef DEBUG
           asprintf(&dbgtext,"allocating memory for %i messages",m_mailbox.total);
           mailplg_debug_handler(dbgtext);
           free(dbgtext);
         #endif
         m_mailbox.header_summary=malloc((sizeof(char *) * m_mailbox.total ));

	/* create message summary */
         for (m_mailbox.msgno = 1; m_mailbox.msgno <= m_mailbox.total; m_mailbox.msgno++)
           { 
	     mu_message_t msg;
             mu_header_t hdr;

           if ((status = mu_mailbox_get_message (m_mailbox.mbox, m_mailbox.msgno, &msg)) != 0
               || (status = mu_message_get_header (msg, &hdr)) != 0)
             {
               #ifdef DEBUG
                 asprintf(&dbgtext,"Error %s",mu_strerror (status));
                 mailplg_debug_handler(dbgtext);
                 free(dbgtext);
               #endif
               mailplg_error_handler("Error",mu_strerror (status)); 
	       return;

             }
           /* extract sender from header */
           if (mu_header_aget_value (hdr, MU_HEADER_FROM, &from))
             from = strdup ("(NO FROM)");
           /* extract subject from header */
           if (mu_header_aget_value (hdr, MU_HEADER_SUBJECT, &subject))
             subject = strdup ("(NO SUBJECT)");
           /* extract send time from header */
           if (mu_header_aget_value (hdr, MU_HEADER_DATE, &date))
             subject = strdup ("(NO DATE)");

           /* convert subject and sender to local charset*/
           mu_rfc2047_decode(charset,subject,&subjectutf);
           mu_rfc2047_decode(charset,from,&fromutf);

           /* create short version of date */
           strptime(date,"%a, %d %b %Y %T",&mailtime);
           strftime(shorttime,sizeof(shorttime), "%d/%m/%y %R", &mailtime);
	   
	   /* store header summary */

	   asprintf(&m_mailbox.header_summary[m_mailbox.msgno -1 ],"%s  %-28.28s  %-25.25s\n",shorttime, fromutf, subjectutf);
          #ifdef DEBUG
            asprintf(&dbgtext,"added summary %s to array",m_mailbox.header_summary[m_mailbox.msgno -1 ]);
            mailplg_debug_handler(dbgtext);
            free(dbgtext);
          #endif

          }
           /* cleanup */
           #ifdef DEBUG
             asprintf(&dbgtext,"freeing from");
             mailplg_debug_handler(dbgtext);
             free(dbgtext);
           #endif
	   if (from != NULL)
             free (from);
           #ifdef DEBUG
             asprintf(&dbgtext,"freeing subject");
             mailplg_debug_handler(dbgtext);
             free(dbgtext);
           #endif
	   if (subject != NULL)
             free (subject);
           #ifdef DEBUG
             asprintf(&dbgtext,"freeing date");
             mailplg_debug_handler(dbgtext);
             free(dbgtext);
           #endif
	   if (date != NULL)
             free (date);
         }

     }
    #ifdef DEBUG
      asprintf(&dbgtext,"leaving mailplg_get_messages function\n");
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif
}

static int mailplg_event_handler(event_t *event)
{
        #ifdef DEBUG
          asprintf(&dbgtext,"entering mailplg_event_handler function, rc_state=%i",rc_state);
          mailplg_debug_handler(dbgtext);
          free(dbgtext);
        #endif

        /* if you press remote key, 3 kind of event(up/repeat/send) is sended to S/W  */
        if( event_key_2value(event) == event_key_value_up )
                return 0 ;

        /* convert event to key value */
        int key = event_key_2code( event );


      if (  rc_state == RC_ACCOUNT ) {
        if( key == KEY_BACK)
                return -1;

        if( key == KEY_OK)
        {
		/* copy mailboxurl */
		m_mailbox.mailboxurl=malloc((strlen(m_accounts.url[m_accounts.focus]) + 1));
	 	strcpy(m_mailbox.mailboxurl,m_accounts.url[m_accounts.focus]);
		mailplg_get_messages();
		/* continue if we had no error */
 		if ( errorstate == 0) {
		  rc_state=RC_HEADER;
		  mailplg_disp_header();
		}
                return 0;
        }

        if( key == KEY_DOWN)
                m_accounts.focus++;
	else if ( key == KEY_PAGEDOWN )
		m_accounts.focus=(m_accounts.focus + MAX_LINE_NUM );
        else if( key == KEY_UP)
                m_accounts.focus--;
	else if ( key == KEY_PAGEUP )
		m_accounts.focus=(m_accounts.focus - MAX_LINE_NUM );

        if(m_accounts.focus < 0)
                m_accounts.focus = 0;
        else if(m_accounts.focus >= m_accounts.nr_accounts)
                m_accounts.focus = m_accounts.nr_accounts-1;

        m_accounts.start_focus =( m_accounts.focus / MAX_LINE_NUM ) * MAX_LINE_NUM;


        mailplg_account_update();

        return 0;

     } else if  (rc_state == RC_ERROR) {
             if( key == KEY_BACK) {
                     return -1;
             }
 	return 0;

    } else if (rc_state == RC_HEADER) { 
        if( key == KEY_BACK) {
                return -1;
         }
              

	
	if ( key == KEY_MENU ) {
                /* close mailbox */
		if (m_mailbox.mbox) {
                  mu_mailbox_close (m_mailbox.mbox);
                  mu_mailbox_destroy (&m_mailbox.mbox);
		}
		rc_state = RC_ACCOUNT;
		m_mailbox.focus=0;
        	mailplg_account_update();
		return 0;
	}

        if( key == KEY_OK)
        {
		if (m_mailbox.total > 0) {
		  rc_state=RC_MESSAGE;
                  mailplg_disp_message();
		  return 0;
		}
        }

        if( key == KEY_DOWN)
                m_mailbox.focus++;
	else if ( key == KEY_PAGEDOWN )
		m_mailbox.focus=(m_mailbox.focus + MAX_LINE_NUM );
        else if( key == KEY_UP)
                m_mailbox.focus--;
	else if ( key == KEY_PAGEUP )
		m_mailbox.focus=(m_mailbox.focus - MAX_LINE_NUM );

        if(m_mailbox.focus >= m_mailbox.total)
                m_mailbox.focus = m_mailbox.total -1 ;
        if(m_mailbox.focus < 0)
                m_mailbox.focus = 0;

        m_mailbox.start_focus =( m_mailbox.focus / MAX_LINE_NUM ) * MAX_LINE_NUM;

	mailplg_disp_header();

    	return 0;
    } else if (rc_state == RC_MESSAGE) { 
        if( key == KEY_BACK)
                return -1;
	
	if ( key == KEY_MENU ) {
		rc_state = RC_HEADER;
        	mailplg_disp_header();
		return 0;
	}

	if ( key == KEY_PAGEDOWN )
		m_message.focus=(m_message.focus + MAX_LINE_NUM );
	else if ( key == KEY_PAGEUP )
		m_mailbox.focus=(m_message.focus - MAX_LINE_NUM );

        if(m_message.focus < 0)
                m_message.focus = 0;
        else if(m_message.focus >= m_message.lines)
                m_message.focus = m_message.lines - 1;

        m_message.start_focus =( m_message.focus / MAX_LINE_NUM ) * MAX_LINE_NUM;

	mailplg_disp_message();

    	return 0;
    }

    return 0;
    #ifdef DEBUG
      asprintf(&dbgtext,"leaving mailplg_event_handler function\n");
      mailplg_debug_handler(dbgtext);
      free(dbgtext);
    #endif
}

static void mailplg_error_handler(char *errdescr,const char *errstring)
{
  #ifdef DEBUG
    asprintf(&dbgtext,"entering mailplg_error_handler function: %s %s", errdescr,errstring);
    mailplg_debug_handler(dbgtext);
    free(dbgtext);
  #endif

  rc_state=RC_ERROR;
  errorstate=1;

  struct _font font = { .size = 18 };
  char *fullmessage;

  asprintf(&fullmessage,"%s: %s\n",errdescr,errstring);

  gc_set_fc(window->gc,0x00c3c4c5);
  gc_set_bc(window->gc,0x00c3c4c5);
  gt_fillrect(&window->fb,window->gc, 0,0,720,576);

  gc_set_fc(window->gc,0x00000000); 
  gc_set_bc(window->gc,0x00ff00ff);


  font_draw_str(
    &font,fullmessage,strlen(fullmessage),
    &window->fb,window->gc,
    60,30);

  wm_redraw(window);
  wm_show(window);

  #ifdef DEBUG
    asprintf(&dbgtext,"freeing fullmessage");
    mailplg_debug_handler(dbgtext);
    free(dbgtext);
  #endif
  free (fullmessage);

  #ifdef DEBUG
    asprintf(&dbgtext,"leaving mailplg_error_handler function: %s %s\n", errdescr,errstring);
    mailplg_debug_handler(dbgtext);
    free(dbgtext);
  #endif

}

static void mailplg_cleanup(void)
{
       #ifdef DEBUG
         asprintf(&dbgtext,"entering mailplg_cleanup_handler function");
         mailplg_debug_handler(dbgtext);
         free(dbgtext);
       #endif

       struct stat tmp_bg_image;
       int counter;

       /* close mailbox */
       if (m_mailbox.mbox) {
         #ifdef DEBUG
           asprintf(&dbgtext,"closing and destroying mailbox");
           mailplg_debug_handler(dbgtext);
           free(dbgtext);
         #endif
         mu_mailbox_close (m_mailbox.mbox);
         mu_mailbox_destroy (&m_mailbox.mbox);
       }

       /* close remote event module */
       #ifdef DEBUG
         asprintf(&dbgtext,"closing event module");
         mailplg_debug_handler(dbgtext);
         free(dbgtext);
       #endif
       plug_event_close();

       /* destroy window */
       #ifdef DEBUG
         asprintf(&dbgtext,"destroy window");
         mailplg_debug_handler(dbgtext);
         free(dbgtext);
       #endif
       wm_destroy(window);

       /* if bg file is tmp */
       stat(plug_bgbmp,&tmp_bg_image);
       if((S_ISREG(tmp_bg_image.st_mode))) {
         #ifdef DEBUG
           asprintf(&dbgtext,"removing tmp bmp file");
           mailplg_debug_handler(dbgtext);
           free(dbgtext);
         #endif
         unlink(plug_bgbmp);
	}

      /* free accounts memory */
      for (counter=0; counter < m_accounts.nr_accounts  ; counter++ ) {
         #ifdef DEBUG
           asprintf(&dbgtext,"freeing account: %s:%s",m_accounts.descr[counter],m_accounts.url[counter]);
           mailplg_debug_handler(dbgtext);
           free(dbgtext);
	 #endif
        free (m_accounts.descr[counter]);
        free (m_accounts.url[counter]);

      }

      #ifdef DEBUG
        asprintf(&dbgtext,"freeing m_accounts.descr and m_accounts.url");
        mailplg_debug_handler(dbgtext);
        free(dbgtext);
      #endif
      free (m_accounts.descr);
      free (m_accounts.url);

      /* free header memory */
      for (counter=0; counter < m_mailbox.nr_messages; counter++ ) {
         #ifdef DEBUG
           asprintf(&dbgtext,"freeing header summary: %s",m_mailbox.header_summary[counter]);
           mailplg_debug_handler(dbgtext);
           free(dbgtext);
	 #endif
        free(m_mailbox.header_summary[counter]);
      }
      #ifdef DEBUG
        asprintf(&dbgtext,"freeing m_mailbox.header_summary and m_mailbox.mailboxurl");
        mailplg_debug_handler(dbgtext);
        free(dbgtext);
      #endif
      free (m_mailbox.header_summary);
      free (m_mailbox.mailboxurl);

      #ifdef DEBUG
        asprintf(&dbgtext,"leaving mailplg_cleanup_handler function\n");
        mailplg_debug_handler(dbgtext);
        free(dbgtext);
      #endif

}

#ifdef DEBUG
static void mailplg_debug_handler(char *debugtext)
{
  fprintf(dbgfilefh,"%s\n",debugtext);
  fflush(dbgfilefh);
}
#endif
