package org.maachang.comet.net.nio ;

import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

import org.maachang.comet.net.ssl.SslOption;
import org.maachang.util.thread.LoopThread;

/**
 * NIO-SSLシングルサーバ処理.
 * 
 * @version 2008/05/28
 * @author  masahito suzuki
 * @since   MaachangComet 1.1B
 */
class NioSingleSslServer extends LoopThread {
    
    /**
     * ログ.
     */
    //private static final Log LOG = LogFactory.getLog( NioSingleSslServer.class ) ;
    
    /**
     * サーバソケット.
     */
    private ServerSocket serverSocket = null ;
    
    /**
     * サーバソケットチャネル.
     */
    private ServerSocketChannel server = null ;
    
    /**
     * セレクタ.
     */
    private Selector selector = null ;
    
    /**
     * 書き込み可能キュー.
     */
    private IsWriteQueue isWriteQueue = null ;
    
    /**
     * 受信処理キュー.
     */
    private ReceiveLinkQueue executionQueue = null ;
    
    /**
     * SSLOption.
     */
    private SslOption option = null ;
    
    /**
     * コンストラクタ.
     */
    private NioSingleSslServer() {
        
    }
    
    /**
     * コンストラクタ.
     * @param channel 対象のサーバソケットを設定します.
     * @param option 対象のSSLオプションを設定します.
     * @param executionQueue 受信実行スレッドとリンクするキューを設定します.
     * @exception Exception 例外.
     */
    public NioSingleSslServer( ServerSocketChannel channel,SslOption option,ReceiveLinkQueue executionQueue )
        throws Exception {
        if( channel == null || executionQueue == null || option == null ) {
            throw new IllegalArgumentException( "引数は不正です" ) ;
        }
        this.serverSocket = channel.socket() ;
        this.serverSocket.setReuseAddress( true ) ;
        this.server = channel ;
        this.selector = Selector.open() ;
        this.option = option ;
        this.server.register( this.selector,SelectionKey.OP_ACCEPT ) ;
        this.isWriteQueue = new IsWriteQueue() ;
        this.executionQueue = executionQueue ;
        this.startThread() ;
    }
    
    /**
     * デストラクタ.
     */
    protected void finalize() throws Exception {
        this.destroy() ;
    }
    
    /**
     * オブジェクト破棄.
     */
    public void destroy() {
        super.stopThread() ;
    }
    
    /**
     * オブジェクトクリア.
     */
    protected void clear() {
        if( this.selector != null ) {
            try {
                Iterator itr = this.selector.keys().iterator();
                while(itr.hasNext()){
                    try {
                        NioTcpUtil.destroyKey( (SelectionKey)itr.next() ) ;
                    } catch( Exception ee ) {
                    }
                }
            } catch(Exception e) {}
        }
        this.selector = null ;
        if( this.server != null ) {
            try {
                this.server.close() ;
            } catch( Exception e ) {
            }
        }
        if( this.serverSocket != null ) {
            try {
                this.serverSocket.close() ;
            } catch( Exception e ) {
            }
        }
        this.serverSocket = null ;
        this.server = null ;
        this.isWriteQueue = null ;
        this.executionQueue = null ;
        this.option = null ;
    }
    
    /**
     * 実行処理.
     * @exception Exception 例外.
     */
    protected boolean execution() throws Exception {
        NioTcpUtil.isWrite( isWriteQueue ) ;
        while ( selector.select() > 0 ) {
            Iterator itr = selector.selectedKeys().iterator() ;
            while(itr.hasNext()) {
                NioTcpUtil.isWrite( isWriteQueue ) ;
                SelectionKey key = ( SelectionKey )itr.next() ;
                itr.remove() ;
                // keyが存在しない場合.
                if( key == null ) {
                    continue ;
                }
                // use-socket.
                if( key.isValid() == false ) {
                    NioTcpUtil.destroyKey( key ) ;
                    continue ;
                }
                // accept.
                else if( NioSslUtil.toAcceptBySingle( selector,key,isWriteQueue,option ) == false ) {
                    // read.
                    NioSslUtil.isRead( selector,key,executionQueue ) ;
                    // write.
                    NioSslUtil.isWrite( selector,key,executionQueue ) ;
                }
            }
        }
        return true ;
    }
    
    /**
     * 例外ハンドラ.
     */
    protected void toException( Throwable e ) {
        //LOG.warn( "error",e ) ;
    }
}
