/* frontend.c */

/* RISC OS front-end for Bombz */

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

#include "DeskLib:Error.h"
#include "DeskLib:Event.h"
#include "DeskLib:Handler.h"
#include "DeskLib:Icon.h"
#include "DeskLib:Menu.h"
#include "DeskLib:MsgTrans.h"
#include "DeskLib:Resource.h"
#include "DeskLib:Template.h"
#include "DeskLib:WimpSWIs.h"

#include "bombz.h"
#include "bsound.h"
#include "choices.h"
#include "key.h"
#include "templates.h"

/* Menu */
static menu_ptr ibar_menu;
#define menu_INFO 0
#define menu_CHOICES 1
#define menu_QUIT 2

static msgtrans_filedesc *messages;

BOOL iconbar_click(event_pollblock *event,void *ref)
{
  if (event->data.mouse.button.data.menu)
    Menu_Show(ibar_menu,event->data.mouse.pos.x,-1);
  else
  {
    if (choices_nicekeys)
      key_use_bkeys();
    else
      key_use_cursors();
    init_sound();
    bombz_title(choices_display,messages);
    reset_sound();
    key_flush_buffer();
  }

  return TRUE;
}

BOOL ibar_menu_handler(event_pollblock *event,void *ref)
{
  if (event->data.selection[0] == menu_QUIT)
    exit(0);

   return TRUE;
}

BOOL use_3D()
{
  return TRUE;
}

void initialise(char *appname)
{
  char filename[128];
  icon_handle baricon;
  window_handle proginfo,choices_diag;

  Resource_Initialise("Bombz");

  /* Load messages */
  sprintf(filename,"%sMessages",resource_pathname);
  Error_CheckFatal(MsgTrans_LoadFile(&messages,filename));

  /* Start up task */
  Event_Initialise(appname);

  /* Put icon on icon bar */
  sprintf(filename,"!%s",appname);
  baricon = Icon_BarIcon(filename,iconbar_RIGHT);

  /* Create windows (loading choices) */
  if (use_3D())
    sprintf(filename,"%sTemplate3D",resource_pathname);
  else
    sprintf(filename,"%sTemplates",resource_pathname);
  Error_CheckFatal(Wimp_OpenTemplate(filename));
  proginfo = templates_create("ProgInfo");
  sprintf(filename,"%sChoices",resource_pathname);
  choices_diag = choices_init(filename);
  Wimp_CloseTemplate();

  /* Open and close handlers */
  Event_Claim(event_OPEN,event_ANY,event_ANY,Handler_OpenWindow,0);
  Event_Claim(event_CLOSE,event_ANY,event_ANY,Handler_CloseWindow,0);

  /* Create menu */
  MsgTrans_Lookup(messages,"Menu:Info,Choices,Quit",filename,256);
  ibar_menu = Menu_New(appname,filename);
  Menu_AddSubMenu(ibar_menu,menu_INFO,(menu_ptr) proginfo);
  Menu_AddSubMenu(ibar_menu,menu_CHOICES,(menu_ptr) choices_diag);
  Event_Claim(event_MENU,event_ANY,event_ANY,ibar_menu_handler,0);

  /* Icon bar icon handler */
  Event_Claim(event_CLICK,window_ICONBAR,baricon,iconbar_click,0);

  bombz_initialise();
  bsound_initialise();
}

int main()
{
  initialise("Bombz");
  while (TRUE)
    Event_Poll();
}
