/*
 * DANG_BEGIN_MODULE
 *
 * Description:
 *   Handles generic virtual console detaching
 * 
 * DANG_END_MODULE
 *
 * $Date: $
 * $Source: $
 * $Revision: $
 * $State: $
 *
 * $Log: $
 */


#include "dosemu.h"
#include "base/detach.h"

static vc_handler_t  handlers[MAX_DETACH_HANDLERS];
static int           detach_handlers = 0;
static Boolean       detaching = FALSE;
static Boolean       attaching = FALSE;

static void vc_detach_lock(void)
{
  detaching = TRUE;
}

static void vc_detach_unlock(void)
{
  detaching = FALSE;
}

static void vc_attach_lock(void)
{
  attaching = TRUE;
}

static void vc_attach_unlock(void)
{
  attaching = FALSE;
}

void vc_register_handler(vc_handler_t info)
{
  if (detach_handlers >= MAX_DETACH_HANDLERS) {
    error("VC: Too many VC handlers!  Increase MAX_DETACH_HANDLERS\n");
    leavedos(1);
  }
  handlers[detach_handlers++] = info;
}

void vc_detach(void)
{
  int i;

  v_printf("VID: vc_detach\n");
  if (!detaching && !attaching) {
    vc_detach_lock();
    for (i = 0; i < detach_handlers; i++)
      handlers[i].detach();
    vc_detach_unlock();
    own_console = FALSE;
  }
  else
    v_printf("VID: vc_detach, %saching\n", (detaching) ? "det" : "att");
}

void vc_attach(void)
{
  int i;

  v_printf("VID: vc_attach\n");
  if (!detaching && !attaching) {
    vc_attach_lock();
    for (i = 0; i < detach_handlers; i++)
      handlers[i].attach();
    vc_attach_unlock();
    own_console = TRUE;
  }
  else
    v_printf("VID: vc_attach failed, %saching\n", (detaching) ? "det" : "att");
  v_printf("VID: vc_attach, done\n");
}
