package com.eactive.eai.adapter.socket2.protocol.http;

import com.eactive.eai.adapter.socket2.protocol.http.codec.HttpProtocolCodecFactory;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;

import java.net.InetSocketAddress;


public class Server {
    /** Default HTTP port */
    private static final int DEFAULT_PORT = 8080;

    /** Tile server revision number */
    public static final String VERSION_STRING = "";

    public static void main(String[] args) {
        int port = DEFAULT_PORT;

        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-port")) {
                port = Integer.parseInt(args[i + 1]);
            }
        }

        try {
            // Create an acceptor
            IoAcceptor acceptor = new SocketAcceptor();

            // Create a service configuration
            SocketAcceptorConfig cfg = new SocketAcceptorConfig();
            cfg.setReuseAddress(true);
            cfg.getFilterChain().addLast(
                    "protocolFilter",
                    new ProtocolCodecFilter(
                            new HttpProtocolCodecFactory(null)));
            cfg.getFilterChain().addLast("logger", new LoggingFilter());

            acceptor
                    .bind(new InetSocketAddress(port), new ServerHandler(), cfg);

            // System.out.println("Server now listening on port " + port);
        } catch (Exception ex) {
//            ex.printStackTrace();
        	// System.out.println("Error" + ex.toString());
        }
    }
}
