package org.maachang.comet.httpd.engine.session ;

import java.net.InetAddress;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.maachang.comet.mdbm.SingleMDbm;
import org.maachang.conf.Config;
import org.maachang.conf.ReadConfigUtil;
import org.maachang.connector.EchoClientConnector;
import org.maachang.session.client.PSessionManager;
import org.maachang.session.client.local.PSessionLocalDriver;
import org.maachang.session.client.net.PSessionNetDriver;
import org.maachang.session.engine.PersistenceDefine;
import org.maachang.util.FileUtil;

/**
 * セッションサービス.
 *
 * @version 2008/05/26
 * @author  masahito suzuki
 * @since   MaachangComet 1.1A
 */
public class SessionService {
    
    /**
     * LOG.
     */
    private static final Log LOG = LogFactory.getLog( SessionService.class ) ;
    
    /**
     * PSession通信ヘッダ.
     */
    private static final byte[] HEADER_BINARY = PersistenceDefine.PROTOCOL_HEADER ;
    
    /**
     * PSessionデフォルトバインドポート.
     */
    public static final int BIND_PORT = PersistenceDefine.BIND_PORT ;
    
    /**
     * セッションコンフィグ.
     */
    private static final String SESSION_CONF = "./conf/session.conf" ;
    
    /**
     * セッションマネージャを取得.
     * @exception Exception 例外.
     */
    public static final HttpdSessionManager getManager() throws Exception {
        HttpdSessionManager ret = null ;
        Config conf = new Config() ;
        if( FileUtil.isFileExists( SESSION_CONF ) ) {
            ReadConfigUtil.readConfig( conf,SESSION_CONF ) ;
            if( conf.isSection( "session-client" ) &&
                conf.getBoolean( "session-client","flag",0 ) == true ) {
                InetAddress addr = conf.getInetAddress( "session-client","connect-address",0 ) ;
                if( addr == null ) {
                    addr = InetAddress.getByName( "127.0.0.1" ) ;
                }
                int port = conf.getInt( "session-client","connect-port",0 ) ;
                if( port <= -1 ) {
                    port = BIND_PORT ;
                }
                if( EchoClientConnector.echo( HEADER_BINARY,addr,port ) == true ) {
                    PSessionManager m = PSessionNetDriver.getConnection( addr,port ) ;
                    if( m != null ) {
                        LOG.info( " ++ PSEサーバ(PersistenceSessionサーバ)に接続" ) ;
                        LOG.info( " ++ addr:" + addr.getHostAddress() + " port:" + port ) ;
                        ret = new HttpdSessionManager( m ) ;
                    }
                    m = null ;
                }
            }
        }
        if( ret == null ) {
            LOG.info( " ++ PSEローカルで接続" ) ;
            ret = new HttpdSessionManager(
                PSessionLocalDriver.getConnection( SingleMDbm.getInstance().getMDbm() ) ) ;
        }
        return ret ;
    }
    
}

