/* Implementation of TMConnectionObserver class.
   Written by Tiggr <tiggr@es.ele.tue.nl> and Michael <michael@thi.nl>

   Copyright (C) 1994, 1995 Pieter J. Schoenmakers and Michael L.H. Brouwer.
   All rights reserved.

   This file is part of RUNNER.

   RUNNER is free software; you can redistribute it and/or modify it
   under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2, or (at
   your option) any later version.

   RUNNER 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 Library General Public
   License for more details.

   You should have received a copy of the GNU Library General Public
   License along with RUNNER; see the file COPYING.LIB.  If not, write
   to the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
   MA 02111-1307, USA.

   $Id: TMConnectionObserver.m,v 1.1 1995/08/25 14:53:11 tiggr Exp $  */

#import <stdio.h>
#import <stdarg.h>
#import <objc/Object.h>
#import <remote/NXConnection.h>
#import <remote/NXProxy.h>
#import "TMConnectionObserver.h"

void
LogError (const char *fmt, ...)
{
  va_list ap;

  va_start (ap, fmt);
  fprintf (stderr, "runner: ");
  vfprintf (stderr, fmt, ap);
  fprintf (stderr, "\n");
  va_end (ap);
} /* LogError */

@implementation TMConnectionObserver

/******************** NXSenderIsInvalid ********************/

/* Be informed of the connection states.  */
-senderIsInvalid: (NXConnection *) connection
{
  int i, n;
  id list;

  /* LogError ("senderIsInvalid: %p", connection); */
  list = [connection remoteObjects];
  for (i = 0, n = [list count]; i < n; i++)
    {
      id p, l;

      p = [list objectAt: i];
      l = [proxies valueForKey: p];
      if (l)
	{
	  [proxies removeKey: p];
	  [l proxyDied: p];
	}
    }
  [list free];
  return (self);
} /* -senderIsInvalid: */

-init
{
  if (![super init])
    return (nil);

  /* The PROXIES maps proxys to local objects.  Since a proxy can vanish
     because the connection is broken, the key description is NOT an ID
     (which would cause `-hash' to be invoked (synchronously!)).  */
  proxies = [[HashTable alloc] initKeyDesc: "!" valueDesc: "@"];
  return (self);
} /* -init */

-(void) registerProxy: (id) proxy forLocal: (id <TMProxyDeath>) local
{
  /* LogError ("%p %p connection: %p", proxy, local, c); */
  if ([proxies insertKey: proxy value: local])
    LogError ("%p %p repeated", proxy, local);
  else
    [[proxy connectionForProxy] registerForInvalidationNotification: self];
} /* -registerProxy:forLocal: */

-(void) unregisterProxy: (id) proxy
{
  if (![proxies valueForKey: proxy])
    LogError ("proxy %p not registered", proxy);
  else
    [proxies removeKey: proxy];
} /* -unregisterProxy: */

@end
