/*
 * Added 01:13pm, Thu 23 Nov 2006 by Chris Terran:
 *   Select on iconbar icon calls Config
 *
 */

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

#include "toolbox.h"
#include "event.h"
#include "gadgets.h"
#include "iconbar.h"
#include "window.h"
#include "wimplib.h"
#include "wimp.h"

#include "xearth.h"
#include "xearthwimp.h"

#define ER(x) if (x != NULL) wimp_report_error((void*) x, 0, "XEarth")

static MessagesFD    msg_block;
static IdBlock	     id_block;
static ObjectId      IconBar;
static int           task_handle = 0, current_wimp = 0, interested = 0;
static char          directory[32] = "<XEarth$Dir>";
static void          *sprite_area;

static int           e;
static WimpPollBlock pb;
static void          *pw;

static int next_x, next_y, next_cols=-1, draw_now=0, last_draw_time=0;
static char xe_filename[24]="<Wimp$ScrapDir>.XEarth1",
            xe_good_filename[24]="\0";
static char config_cmd[256];

void whinge(char *msg)
{
  _kernel_oserror    err;

  err.errnum = 0;
  strcpy(err.errmess, msg);
  wimp_report_error(&err, 0, "Dallier");
}

static int quit_handler(void)
{
  exit(1);
  return(1);
}

static int autocreate_handler(int event_code, ToolboxEvent *event, IdBlock *id_block, void *h)
{
  ToolboxObjectAutoCreatedEvent    *event_a;

  event_a = (ToolboxObjectAutoCreatedEvent*) event;

  if (strcmp(event_a->template_name, "IconBar") == 0)
  {
    IconBar = id_block->self_id;
    if (!no_icon)
    {
      ER(toolbox_show_object(0, IconBar, 0, NULL, 0, 0));
      ER(iconbar_set_sprite(0, IconBar, "xearth_go"));
    }
  }

  return(1);
}

static int last_poll_time=0;

extern int poll_wimp(void)
{
  if (draw_now) return(PollAbort);

  if ( *((int*)0x10c) - last_poll_time >= 1 )
  {
    last_poll_time = *((int*)0x10c);
    event_poll(&e, &pb, &pw);
  }
  return(PollNormal);
}

static void modechange(void)
{
  read_mode_vars(&next_x, &next_y, &next_cols);
  if (next_cols == 1 || next_cols == 3 || next_cols == 15) next_cols = 2;
  if (next_cols == 63|| next_cols == 255) next_cols = 12;
  if (next_cols == 65535) next_cols = 1<<24; // 16bpp == 24bpp for now
  if (next_cols == -1) next_cols = 1<<24;
  next_y-=59; next_x++;
}

static int modechange_handler(void)
{
  char cmd[256];

  modechange();

  /* don't start new redraw unless we've actually changed mode */

  if (next_x == wdth && next_y == hght && next_cols == num_colors)
  /* Next line changed from   return;   04:25pm, Sat 18 Nov 2006 CJT */
    return(1);

  sprintf(cmd, "Backdrop -scale %s", xe_good_filename);

  draw_now = 1;

  if (xe_good_filename[0] != 0)
    system(cmd);
  return(1);
}

static int render_handler(void)
{
  draw_now = 1;
  return(1);
}

static int config_handler(void)
/* Select on iconbar icon
   If !Confix is present call it, else present the text config file to the user
   Command line is:
     WimpTask <Confix$Dir> -res <XEarth$Dir> -file XEarth:Choices -task [handle] -pos right,iconbar"
*/
{
/*  sprintf(config_cmd, "WimpTask <Confix$Dir> -res <XEarth$Dir>.Conf -file XEarth:Conf.Choices -task %d -pos right,iconbar", task_handle); */
  sprintf(config_cmd, "WimpTask XEarth:Conf.DoConf -task %d", task_handle);
  system(config_cmd);
  return(1);
}

extern int wimp_output(void)
{
  FILE          *out;

  ER(event_initialise(&id_block));
  ER(toolbox_initialise(0, 310, &interested, &interested, directory,
                     &msg_block, &id_block, &current_wimp, &task_handle,
                     &sprite_area));

  ER(event_register_message_handler(Wimp_MQuit, (WimpMessageHandler*) quit_handler, NULL));
  ER(event_register_message_handler(Wimp_MModeChange, (WimpMessageHandler*) modechange_handler, NULL));
/*  ER(event_register_message_handler(ConfiX_MGeneric, (WimpMessageHandler*) confix_msg_handler, NULL)); */
  ER(event_register_toolbox_handler(-1, XEarth_EventQuit, (ToolboxEventHandler*) quit_handler, NULL));
  ER(event_register_toolbox_handler(-1, XEarth_EventRender, (ToolboxEventHandler*) render_handler, NULL));
  ER(event_register_toolbox_handler(-1, XEarth_EventConfig, (ToolboxEventHandler*) config_handler, NULL));
  ER(event_register_toolbox_handler(-1, Toolbox_ObjectAutoCreated, autocreate_handler, NULL));
  event_set_mask(!Wimp_Poll_NullMask);

  // call mode change handler for initial render
  modechange();

  while (1)
  {
    char cmd[256];

    wdth = next_x; hght = next_y; num_colors = next_cols;
    draw_now = 0;
    iconbar_set_sprite(0, IconBar, "xearth_go");
    compute_positions();
    scan_map();
    do_dots();
    if (xe_filename[strlen(xe_filename)-1] == '1')
      xe_filename[strlen(xe_filename)-1] = '2';
    else
      xe_filename[strlen(xe_filename)-1] = '1';
    out = fopen(xe_filename, "wb");
    //whinge(xe_filename);
    if (!out) whinge("Couldn't open output file!"), exit(1);
    sprite_setup(out);
    render(sprite_row);
    if (!fclose(out)) /*whinge("couldn't close file!")*/;
    sprite_cleanup();
    strcpy(xe_good_filename, xe_filename);
    sprintf(cmd, "SetType %s Sprite", xe_filename); system(cmd);
    sprintf(cmd, "Backdrop -centre %s", xe_filename);
    if (!draw_now)
      system(cmd);
    last_draw_time = *((int*)0x10C);
    ER(iconbar_set_sprite(0, IconBar, "!xearth"));

    /*if (do_once)
      return(0);*/

    while ( *((int*)0x10C) - last_draw_time < (wait_time*100) &&
            !draw_now)
      event_poll_idle(&e, &pb, *((int*)0x10C)+100, &pw);
  }

  return(0);
}
