/* Digital Clock for Bad Seal 0.53 ONLY (placed on userbox) */

#include "allegro.h"
#include "seal.h"
#include "app.h"
#include "dialogs.h"
#include "desktop.h"
#include "dos.h"
#include "registry.h"

l_color face3d;

typedef struct t_clock *p_clock;

typedef struct t_clock {

  struct t_view obclass;

  char *text;

} t_clock;

void clock_draw(p_view o)
{
  t_rect r = o->get_local_extent(o);
  t_point p;
  BITMAP *out = o->begin_paint(o, &p, r);

  if (out) {
    rectfill(out, r.a.x+p.x, r.a.y+p.y, r.b.x+p.x, r.b.y+p.y, face3d);
    textout_draw_rect(out, o->font, ((p_clock)(o))->text, -1, r.a.x+p.x, r.a.y+p.y, r.b.x+p.x, r.b.y+p.y, TX_ALIGN_CENTER, COLOR(0), face3d, 0);
  };

  o->end_of_paint(o, r);
};

t_point clock_size_minimum(p_view o)
{
  return point_assign(0, 0);
};

p_clock _clock_init(p_clock o, t_rect r)
{
  if (!o) return NULL;

  clear_type(o, sizeof(t_clock));

  view_init(&o->obclass, r);

  o->text = (char *) malloc(9);

  VIEW(o)->draw = &clock_draw;
  VIEW(o)->size_minimum = &clock_size_minimum;

  return o;
};

p_clock (*clock_init)(p_clock o, t_rect r) = &_clock_init;

p_clock clock;

void refresh(p_object o)
{
  struct time t;
  char s[4];
  char ampm[3] = "am";
  gettime(&t);
  OBJECT(o)->process_tick=60000-t.ti_sec*1000; /* call me back next time minutes changes */
  if (t.ti_hour > 12)
  {
    t.ti_hour -= 12;
    strcpy(ampm, "pm");
  };

  itoa(t.ti_hour, s, 10);
  strcpy(clock->text, s);
  strcat(clock->text, ":");
  itoa(t.ti_min, s, 10);
  strcat(clock->text, s);
  strcat(clock->text, ampm);

  VIEW(clock)->draw(VIEW(clock));
};

app_begin(void)
{
  if (ap_process == AP_INIT) {
    t_rect r = rect_assign(0, 0, 45, 15);
    AP_SETNUMOFCALLS(1);
    face3d=COLOR(0);
    iffound(face3d , registry_color("3d_face"));

    clock = clock_init(malloc(sizeof(t_stattext)), r);
    VIEW(clock)->change_bounds(VIEW(clock), r);
    OBJECT(clock)->process_tick = 100;
    OBJECT(clock)->func_callback = &refresh;
    add_to_userbox(OBJECT(clock));
    init_stillprocess(OBJECT(clock), 100);
  };
} app_end;

