#include "test_config.h"
#include "ace/Service_Config.h"
#include "ace/Reactor.h"
#include "ace/Log_Msg.h"
#include "ace/Signal.h"

static bool handleA_close_called = false;
static bool handleB_close_called = false;

class My_HandlerA : public ACE_Event_Handler
{
public:
  virtual int handle_close (ACE_HANDLE,
                            ACE_Reactor_Mask)
  {
    ACE_DEBUG ((LM_DEBUG,
                "Handle close called\n"));
    handleA_close_called = true;

    return 0;
  }

  virtual int handle_signal (int,
                             siginfo_t *,
                             ucontext_t *)
  {
    ACE_DEBUG ((LM_DEBUG,
                "Handle signal called\n"));

    return 0;
  }
};

class My_HandlerB : public ACE_Event_Handler
{
public:
  virtual int handle_close (ACE_HANDLE,
                            ACE_Reactor_Mask)
  {
    ACE_DEBUG ((LM_DEBUG,
                "Handle close called\n"));
    handleB_close_called = true;

    return 0;
  }

  virtual int handle_signal (int,
                             siginfo_t *,
                             ucontext_t *)
  {
    ACE_DEBUG ((LM_DEBUG,
                "Handle signal called\n"));

    return 0;
  }
};

int run_main (int, ACE_TCHAR *[])
{
  ACE_START_TEST (ACE_TEXT ("Regression_Test"));

  ACE_Reactor my_reactorA;
  ACE_Reactor my_reactorB;
  
  My_HandlerA my_handlerA;
  My_HandlerB my_handlerB;

  // Set up both of the ACE signal handlers (each assigned to a different reactor).
  ACE_Sig_Set sigSet;
  sigSet.sig_add(SIGINT);
  if (my_reactorA.register_handler
      (sigSet,
       &my_handlerA) == -1)
    ACE_ERROR ((LM_DEBUG,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("register_handlerA")));

  if (my_reactorB.register_handler
      (SIGTERM,
       &my_handlerB) == -1)
    ACE_ERROR ((LM_DEBUG,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("register_handlerB")));
    
  // Close the first reactor
  if (my_reactorA.close() == -1)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("close")));

  if (!handleA_close_called)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("Handle close hasn't been called for A.\n")));

  if (handleB_close_called)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("Handle close has already been called for B.\n")));

  // Close the second reactor
  if (my_reactorB.close() == -1)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("close")));
    
  if (!handleB_close_called)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("Handle close hasn't been called for B.\n")));

  ACE_END_TEST;

  return 0;
}
