/*  gfocustimer
 *  Copyright (C) 1999 James Cameron, <quozl@us.netrek.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <gtk/gtk.h>
#include <gdk/gdkx.h>

#include "callbacks.h"
#include "interface.h"
#include "support.h"
#include "utilities.h"
#include "data.h"
#include "total.h"
#include "entry.h"
#include "charge.h"
#include "preferences.h"
#include "focus.h"
#include "connect.h"

/* main window */
extern struct mw mw;

/* preferences data */
extern struct pd pd;

/* binary tree of windows, keyed by XID */
extern GTree *windows;

/* tags for timeout context */
int connect_timeout_tag = 0;


/* perform connection timeout periodically */
static gint connect_timeout (gpointer data)
{
  Window new, me;
  int ignored;
  struct wd *wd;

  /* get current input focus window */
  XGetInputFocus (gdk_display, &new, &ignored);

  /* ignore the new window if it is my top level main window */
  me = GDK_WINDOW_XWINDOW(mw.widget->window);
  if (new == me) {
    return TRUE;
  }

  /* do we have this window in our binary tree? */
  wd = g_tree_lookup (windows, &new);
  if (wd == NULL) {
    /* no, we do not know of it */

    /* focus has moved to an unknown window during a connection */
    wd = g_new (struct wd, 1);
    wd->window = new;
    g_tree_insert (windows, &wd->window, wd);
  } else {

    /* window is known */
    /* focus has moved during a connection to a known window */
  }

  /* connect window to entry */
  wd->ed = mw.ed;
  wd->connected = time(NULL);

  if (pd.connect_do == CONNECT_DO_BEEP) gdk_beep ();
  entry_highlight_active (wd->ed->row);
  focus_schedule();

  return FALSE;
}


void connect_schedule()
{
  connect_timeout_tag = gtk_timeout_add (pd.connect_time,
					 connect_timeout, NULL);
}


void connect_deschedule()
{
  if (connect_timeout_tag != 0) {
    gtk_timeout_remove (connect_timeout_tag);
    connect_timeout_tag = 0;
  }
}


void connect_reschedule()
{
  if (connect_timeout_tag != 0) {
    connect_deschedule();
    connect_schedule();
  }
}
