/* WCESelector.cpp
   Copyright (C) 2010  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath 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, or (at your option)
any later version.
 
GNU Classpath 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 GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

#include <com_mysaifu_jvm_java_nio_channels_WCESelector.h>

#include <winsock2.h>

#define OP_ACCEPT   16
#define OP_CONNECT  8
#define OP_READ     1
#define OP_WRITE    4

class WCESelector
{
  /**
   * wakeup()でシグナル状態にするイベントオブジェクト
   */
  WSAEVENT hWakeupEvent;

public:
  WCESelector();
  ~WCESelector();

  int waitEvents(int count, SOCKET* sockets, long* events, DWORD timeout);

  void wakeup();

  inline int OPS2EVENTS(int ops)
  {
    int ev = 0;
    
    if (ops & OP_ACCEPT)
    {
      ev |= FD_ACCEPT;
    }
    if (ops & OP_CONNECT)
    {
      ev |= FD_CONNECT;
    }
    if (ops & OP_READ)
    {
      ev |= FD_READ;
    }
    if (ops & OP_WRITE)
    {
      ev |= FD_WRITE;
    }
    return ev;
  }

  inline int EVENTS2OPS(int events)
  {
    int ops = 0;
    if (events & FD_ACCEPT)
    {
      ops |= OP_ACCEPT;
    }
    if (events & FD_CONNECT)
    {
      ops |= OP_CONNECT;
    }
    if (events & FD_READ)
    {
      ops |= OP_READ;
    }
    if (events & FD_WRITE)
    {
      ops |= OP_WRITE;
    }

    return ops;
  }

};

WCESelector::WCESelector()
{
  this->hWakeupEvent = ::WSACreateEvent();
}

WCESelector::~WCESelector()
{
  ::WSACloseEvent(this->hWakeupEvent);
}

void
WCESelector::wakeup()
{
  ::WSASetEvent(this->hWakeupEvent);
}

int
WCESelector::waitEvents(int count, SOCKET* sockets, long* events, DWORD timeout)
{
  // wakeup()イベントの分1つだけ多く確保する
  WSAEVENT* wsaEvents = new WSAEVENT[count + 1];
  bool error = false;
  for (int i = 0; i < count; ++i)
  {
    SOCKET sock = sockets[i];
    long event = events[i];

    WSAEVENT hEvent = ::WSACreateEvent();
    wsaEvents[i] = hEvent;

    int result = ::WSAEventSelect(sock, hEvent, events[i] | FD_CLOSE);
    if (SOCKET_ERROR == result)
    {
      error = true;
      break;
    }
  }

  int result = 0;
  if (! error)
  {
    // wakeup() イベント
    wsaEvents[count] = this->hWakeupEvent;

    DWORD ret = ::WSAWaitForMultipleEvents(count + 1,
                                           wsaEvents,
                                           FALSE,       // fWaitAll
                                           timeout,     // dwTimeout
                                           FALSE        // fAlertable
                                           );
    if (WSA_WAIT_FAILED == ret
      || WSA_WAIT_TIMEOUT == ret
      || WSA_WAIT_EVENT_0 + count == ret)
    {
      // 失敗またはタイムアウトまたはwakeup()で起こされた場合
      result = 0;
      memset(events, 0, sizeof(long) * count);
    }
    else
    {
      // ネットワークイベントを列挙する
      WSANETWORKEVENTS networkEvents;

      for (int i = 0; i < count; ++i)
      {
        WSAEVENT hEvent = wsaEvents[i];
        if (SOCKET_ERROR == ::WSAEnumNetworkEvents(sockets[i],    // SOCKET
                                                   hEvent,        // 
                                                   &networkEvents //
                                                   ))
        {
          break;
        }

        const long readyEvents = networkEvents.lNetworkEvents;
        if (readyEvents & FD_CLOSE)
        {
          // クローズされてしまった
          events[i] = 0xffffffff;
        }
        else
        {
          // 発生したイベントのみを格納する
          if ((readyEvents & events[i]) != 0)
          {
            // 指定されたイベントのうち、1つ以上が発生した
            result++;
            events[i] = readyEvents;
          }
          else
          {
            // 指定されたイベントは発生しなかった
            events[i] = 0;
          }
        }
      }
    }
  }

  // イベントをクローズする
  // ただし wakeup()イベントはクローズしない
  for (int i = 0; i < count; ++i)
  {
    WSAEVENT hEvent = wsaEvents[i];
    ::WSAEventSelect(sockets[i], hEvent, 0);
    ::WSACloseEvent(hEvent);
  }

  // wakeup()イベントを非シグナル状態にする
  ::WSAResetEvent(this->hWakeupEvent);

  delete wsaEvents;

  return result;
}

/*
 * Class:     com_mysaifu_jvm_java_nio_channels_WCESelector
 * Method:    openNative
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_com_mysaifu_jvm_java_nio_channels_WCESelector_openNative
  (JNIEnv *env, jobject)
{
  return reinterpret_cast<jint>(new WCESelector());
}


/*
 * Class:     com_mysaifu_jvm_java_nio_channels_WCESelector
 * Method:    closeNative
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_com_mysaifu_jvm_java_nio_channels_WCESelector_closeNative
  (JNIEnv *, jobject, jint nativePointer)
{
  if (nativePointer)
  {
    delete reinterpret_cast<WCESelector*>(nativePointer);
  }
}

/*
 * Class:     com_mysaifu_jvm_java_nio_channels_WCESelector
 * Method:    waitNativeEvents
 * Signature: (I[I[IJ)I
 */
JNIEXPORT jint JNICALL Java_com_mysaifu_jvm_java_nio_channels_WCESelector_waitNativeEvents
  (JNIEnv *env, jobject, jint nativePointer, jintArray sockets, jintArray opts, jlong timeout)
{
  if (! nativePointer)
  {
    return 0;
  }

  const jsize count = env->GetArrayLength(sockets);
  if (count != env->GetArrayLength(opts))
  {
    env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"), "sockets.length!=opts.length");
    return 0;
  }

  WCESelector* pSelector = reinterpret_cast<WCESelector*>(nativePointer);

  // パラメータをコピーする
  SOCKET* socketsArray = new SOCKET[count];
  jint* tmp = static_cast<jint*>(env->GetPrimitiveArrayCritical(sockets, NULL));
  memcpy(socketsArray, tmp, sizeof(SOCKET) * count);
  env->ReleasePrimitiveArrayCritical(sockets, tmp, 0);

  int* events = new int[count];
  tmp = static_cast<jint*>(env->GetPrimitiveArrayCritical(opts, NULL));
  for (int i = 0; i < count; ++i)
  {
    events[i] = pSelector->OPS2EVENTS(tmp[i]);
  }
  env->ReleasePrimitiveArrayCritical(opts, tmp, 0);

  DWORD t;
  if (0 == timeout)
  {
    t = WSA_INFINITE;
  }
  else
  {
    t = (DWORD) timeout;
  }

  int result = pSelector->waitEvents(count, socketsArray, reinterpret_cast<long*>(events), t);
  
  
  // 結果を確かめる
  tmp = static_cast<jint*>(env->GetPrimitiveArrayCritical(opts, NULL));
  for (int i = 0; i < count; ++i)
  {
    if (events[i] == 0xffffffff)
    {
      // クローズされてしまった場合
      tmp[i] = events[i];
    }
    else
    {
      tmp[i] = pSelector->EVENTS2OPS(events[i]);
    }
  }
  env->ReleasePrimitiveArrayCritical(opts, tmp, 0);


  delete socketsArray;
  delete events;

  return result;
}

/*
 * Class:     com_mysaifu_jvm_java_nio_channels_WCESelector
 * Method:    wakeupNative
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_com_mysaifu_jvm_java_nio_channels_WCESelector_wakeupNative
  (JNIEnv *, jobject, jint nativePointer)
{
  if (! nativePointer)
  {
    return;
  }

  WCESelector* pSelector = reinterpret_cast<WCESelector*>(nativePointer);
  pSelector->wakeup();
}
