package org.maachang.session ;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.maachang.conf.Config;
import org.maachang.session.engine.PersistenceDefine;
import org.maachang.session.engine.PersistenceService;
import org.maachang.session.server.PSessionServerService;
import org.maachang.shutdown.ShutdownCallback;
import org.maachang.shutdown.ShutdownHook;
import org.maachang.shutdown.WaitShutdown;

/**
 * 永続化セッションサーバプロセス.
 * 
 * @version 2008/05/26
 * @author masahito suzuki
 * @since PersistenceSession 1.00
 */
public class PSessionProcess {
    
    /**
     * ログ.
     */
    private static final Log LOG = LogFactory.getLog( PSessionProcess.class ) ;
    
    /**
     * サーバサービス.
     */
    private PSessionServerService serverService = null ;
    
    private PSessionProcess() {}
    
    /**
     * メイン.
     */
    public static final void main( String[] args ) throws Exception {
        new PSessionProcess().execution() ;
    }
    
    /**
     * サーバ実行.
     */
    private void execution() throws Exception {
        LOG.info( "*** [PSession] startup[version:"+PersistenceDefine.VERSION+"] ***" ) ;
        PersistenceService.getInstance().init() ;
        this.serverService = new PSessionServerService() ;
        int port = getShutdownPort() ;
        ShutdownHook.registHook( new PSessionShutdown( serverService ) ) ;
        WaitShutdown waitDown = new WaitShutdown( port ) ;
        LOG.info( "*** [PSession] startup...[OK]" ) ;
        for( ;; ) {
            if( waitDown.isShutdown() ) {
                waitDown.exitShutdown() ;
                break ;
            }
        }
    }
    
    /**
     * シャットダウンポートを取得.
     * @return int シャットダウンポート番号が返されます.
     */
    public static final int getShutdownPort() throws Exception {
        Config conf = PSessionServerService.readConfig() ;
        int port = conf.getInt( "session","shutdown-port",0 ) ;
        if( port <= 0 ) {
            port = PersistenceDefine.BIND_SHUTDOWN_PORT ;
        }
        return port ;
    }
    
}

/**
 * シャットダウン用コールバック.
 */
class PSessionShutdown extends ShutdownCallback {
    private static final Log LOG = LogFactory.getLog( PSessionShutdown.class ) ;
    private PSessionServerService serverService = null ;
    public PSessionShutdown( PSessionServerService serverService ) {
        this.serverService = serverService ;
    }
    public void execution() {
        LOG.info( "*** [PSession]shutdown." ) ;
        if( this.serverService != null ) {
            this.serverService.destroy() ;
            PersistenceService.getInstance().destroy() ;
        }
        LOG.info( "*** [PSession]shutdown...[OK]" ) ;
    }
}

