/* general include */
#include <picogui.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>


pghandle wMessageBodyBox;
char fpath[1000];


/* update the body of the message regarding selected subject */
int updateBody(struct pgEvent *evt) {
  char body[2060];
  static pghandle wBodyScroll = 0;
  static pghandle wBodyBox = 0;

  FILE *fp;
  char ch;
  int  i;

  /* remove the old messages */
  if(wBodyScroll != 0) {
    pgDelete(wBodyScroll);
    pgDelete(wBodyBox);
  }

  /* open file to display */
  if((fp=fopen(fpath,"r"))==NULL) {
    printf("Error open sample_script.txt\n");
    exit(1);
  }
  /* load file */
  i=0;
  while((ch=getc(fp))!=EOF) {
    if(i<2048) body[i]=ch;
    i++;
  }
  fclose(fp);

  /* create a box for the subjects */
  wBodyBox = pgNewWidget(PG_WIDGET_BOX,PG_DERIVE_INSIDE,wMessageBodyBox);
  pgSetWidget(PGDEFAULT,PG_WP_SIDE,PG_S_ALL,0);

  /* add the scroll bar */
  wBodyScroll = pgNewWidget(PG_WIDGET_SCROLL,PG_DERIVE_BEFORE,wBodyBox);

  /* bind the scroll bar to the subject box */
  pgSetWidget(wBodyScroll,PG_WP_BIND,wBodyBox,0);

  /* make label widget for body of message */
  pgNewWidget(PG_WIDGET_TEXTBOX,PG_DERIVE_INSIDE,wBodyBox);
  pgSetWidget(PGDEFAULT,
              PG_WP_TEXTFORMAT,pgNewString("HTML"),
  	      PG_WP_TEXT,pgNewString(body),
  	      PG_WP_SIDE,PG_S_ALL,
  	      0);

  return 0;
}


/** main **/
int main( int argc, char ** argv ) {
  pghandle wSubjectsBox;
  pghandle wSubjects;


  if(argc<2) {
    printf("usage: pgsmr FILE\n");
    exit(1);
  }

  strcpy(fpath,argv[1]);

  /* init the link with PicoGUI server */
  pgInit( argc, argv );

  pgRegisterApp( PG_APP_NORMAL, "TextBox tester", 0 );

  /* create a box for the subjects */
  wSubjectsBox = pgNewWidget(PG_WIDGET_BOX,0,0);
  pgSetWidget(wSubjectsBox,PG_WP_SIDE,PG_S_LEFT,0);

  /* create a box for the message body */
  wMessageBodyBox = pgNewWidget(PG_WIDGET_BOX,PG_DERIVE_AFTER,wSubjectsBox);
  pgSetWidget(PGDEFAULT,PG_WP_SIDE,PG_S_ALL,0);

  /* create a box for the subjects */
  wSubjects = pgNewWidget( PG_WIDGET_BOX, PG_DERIVE_INSIDE, wSubjectsBox );
  pgSetWidget( PGDEFAULT, PG_WP_SIDE, PG_S_ALL, 0 );
  /* a subject */
  pgNewWidget(PG_WIDGET_FLATBUTTON,PG_DERIVE_INSIDE,0);
  pgSetWidget(PGDEFAULT,
	      PG_WP_SIDE,PG_S_TOP,
	      PG_WP_TEXT,pgNewString("DIE"),
	      0);
  /* binding to update body message */
  pgBind(PGDEFAULT,PG_WE_ACTIVATE,&updateBody,NULL);

  /* the main loop */
  pgEventLoop();

  return 0;
}

/** end **/
