/* Help panel */
/* by Kostas Michalopoulos aka Bad Sector */

#include <process.h>
#include "allegro.h"
#include "seal.h" 
#include "app.h" 
#include "dialogs.h" 
#include "button.h"
#include "helpsys.h"

#define MSG_COMPILE 10001
#define MSG_VIEW 10002

p_appwin main;
p_textline fname;

l_bool compile(l_text fname)
{
  l_bool ok;
  l_text args[] = {
    "helpc",
    fname,
    "-q",
    0
  };
  if (!fname) return 0;

  ok = spawnvp(P_WAIT, "helpc", args);

  return TRUE;
}

static void translate_event(p_object o, p_event event)
{
  if (event->type == EV_MESSAGE)
  {
    switch (event->message)
    {
      case MSG_COMPILE: {
        compile(fname->text);
        clear_event(event);
      } break;
      case MSG_VIEW: {
        l_text hlpfile = NULL;
        l_int i;

        clear_event(event);
        hlpfile = (l_text) malloc(256);
        for (i=0;i<strlen(fname->text);i++)
          if (fname->text[i] == '.') {
            hlpfile[i] = 0;
            strcat(hlpfile, ".hlp");
            break;
          } else hlpfile[i] = fname->text[i];
        open_help(hlpfile);
        free(hlpfile);
        clear_event(event);
      } break;
    };
  };
}

void app_init()
{ 
  t_rect r = rect_assign(0, 0, 200, 130);
  p_button b;

  main = appwin_init(malloc(sizeof(t_appwin)), r, "Help Panel", WF_MINIMIZE, ap_id, &translate_event);
  VIEW(main)->align |= TX_ALIGN_CENTER;
  OBJECT(desktop)->insert(OBJECT(desktop), OBJECT(main));

  r = rect_assign(4, 21, 196, 51);
  b = button_init(malloc(sizeof(t_button)), r, "Compile given file", MSG_COMPILE, 0);
  OBJECT(main)->insert(OBJECT(main), OBJECT(b));

  r = rect_assign(4, 60, 196, 90);
  b = button_init(malloc(sizeof(t_button)), r, "View compiled file", MSG_VIEW, 0);
  OBJECT(main)->insert(OBJECT(main), OBJECT(b));

  r = rect_assign(4, 100, 196, 120);
  fname = textline_init(malloc(sizeof(t_textline)), r, 256, 0);
  OBJECT(main)->insert(OBJECT(main), OBJECT(fname));
}

app_begin(void) 
{ 
  if (ap_process == AP_INIT) { 
    app_init();
  }; 
} app_end;

