/* WCESelector.java -- 
   Copyright (C) 2010 Mysaifu.com

This file is part of Mysaifu JVM.

Mysaifu JVM 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.

Mysaifu JVM 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 Mysaifu JVM; 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. */


package com.mysaifu.jvm.java.nio.channels;

import java.io.IOException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.spi.AbstractSelector;
import java.nio.channels.spi.AbstractSelectableChannel;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class WCESelector
    extends AbstractSelector
{
  static
    {
      System.loadLibrary("javanio");
    }

  private HashSet<SelectionKey> keys = new HashSet<SelectionKey>();

  private HashSet<SelectionKey> selected = new HashSet<SelectionKey>();

  private int nativePointer;

  public WCESelector(WCESelectorProvider provider)
  {
    super(provider);
    this.nativePointer = openNative();
  }

  /**
   * ネイティブライブラリを初期化する
   */
  private native int openNative();

  @Override
  protected void finalize() throws Throwable
  {
    close();
  }

  @Override
  protected void implCloseSelector() throws IOException
  {
    wakeup();
    closeNative(this.nativePointer);
    this.nativePointer = 0;
  }

  /**
   * このセレクタを閉じる
   */
  private native void closeNative(int nativePointer) throws IOException;

  @Override
  public Set<SelectionKey> keys()
  {
    if (! isOpen())
      throw new ClosedSelectorException();

    return Collections.unmodifiableSet(keys);
  }

  @Override
  public int selectNow() throws IOException
  {
    return select(1);
  }

  @Override
  public final int select() throws IOException
  {
    return select(0);
  }

  @Override
  protected SelectionKey register(AbstractSelectableChannel ch, int ops,
                                  Object att)
  {
    WCESelectionKey key = new WCESelectionKey(this, ch);
    synchronized (keys)
      {
        keys.add(key);
        key.interestOps(ops);
        key.attach(att);
      }

    return key;
  }

  @Override
  public synchronized int select(long timeout) throws IOException
  {
    if (! isOpen())
      {
        throw new ClosedSelectorException();
      }

    int result = 0;
    synchronized (keys)
      {
        synchronized (selected)
          {
            deregisterCancelledKeys();

            // SOCKET と interestOps() の対応を int[] に格納する
            final int size = this.keys.size();
            int[] sockets = new int[size];
            int[] ops = new int[size];
            int index = 0;
            for (SelectionKey k : this.keys)
              {
                WCESelectionKey wk = (WCESelectionKey) k;
                sockets[index] = wk.getNativeFD();
                ops[index] = wk.interestOps();
                index++;
              }
            try
              {
                begin();
                result = waitNativeEvents(this.nativePointer, sockets, ops, timeout);
              }
            finally
              {
                end();
              }

            Iterator<SelectionKey> it = keys.iterator();
            index = 0;
            while (it.hasNext())
              {
                WCESelectionKey key = (WCESelectionKey) it.next();
                int op;
                if (this.selected.contains(key))
                  {
                    op = key.readyOps();
                  }
                else
                  {
                    op = ops[index];
                  }
                if (op == 0xffffffff)
                  {
                    key.cancel();
                  }
                else
                  {
                    key.readyOps(op & key.interestOps());
                    this.selected.add(key);
                  }
              }
            deregisterCancelledKeys();
          }
      }
    return result;
  }

  /**
   * イベントの受信処理を行う
   */
  private native int waitNativeEvents(int nativePointer, int[] sockets, int[] opts, long timeout)
      throws IOException;

  @Override
  public Set<SelectionKey> selectedKeys()
  {
    if (! isOpen())
      {
        throw new ClosedSelectorException();
      }

    return new Set<SelectionKey>()
    {
      @Override
      public boolean add(SelectionKey key)
      {
        throw new UnsupportedOperationException();
      }

      @Override
      public boolean addAll(Collection< ? extends SelectionKey> c)
      {
        throw new UnsupportedOperationException();
      }

      @Override
      public void clear()
      {
        selected.clear();

      }

      @Override
      public boolean contains(Object o)
      {
        return selected.contains(o);
      }

      @Override
      public boolean containsAll(Collection< ? > c)
      {
        return selected.containsAll(c);
      }

      @Override
      public boolean equals(Object o)
      {
        return selected.equals(o);
      }

      @Override
      public int hashCode()

      {
        return selected.hashCode();
      }

      @Override
      public boolean isEmpty()
      {
        return selected.isEmpty();
      }

      @Override
      public Iterator<SelectionKey> iterator()
      {
        return selected.iterator();
      }

      @Override
      public boolean remove(Object o)
      {
        return selected.remove(o);
      }

      @Override
      public boolean removeAll(Collection< ? > c)
      {
        return selected.removeAll(c);
      }

      @Override
      public boolean retainAll(Collection< ? > c)
      {
        return selected.retainAll(c);
      }

      @Override
      public int size()
      {
        return selected.size();
      }

      @Override
      public Object[] toArray()
      {
        return selected.toArray();
      }

      @Override
      public <SelectionKey> SelectionKey[] toArray(SelectionKey[] a)
      {
        return selected.toArray(a);
      }

    };
  }

  @Override
  public Selector wakeup()
  {
    wakeupNative(this.nativePointer);
    return this;
  }

  private native void wakeupNative(int nativePointer);

  /**
   * キャンセル済みのキーを削除する。
   */
  private void deregisterCancelledKeys()
  {
    Set<SelectionKey> ckeys = cancelledKeys();
    synchronized (ckeys)
      {
        Iterator<SelectionKey> it = ckeys.iterator();

        while (it.hasNext())
          {
            SelectionKey key = it.next();
            keys.remove(key);
            it.remove();
          }
      }
  }

}
