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

import com.eactive.eai.adapter.socket2.protocol.http.codec.HttpResponse;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.util.SessionLog;


public class ServerHandler extends IoHandlerAdapter {
    @Override
    public void sessionOpened(IoSession session) {
        // set idle time to 60 seconds
        session.setIdleTime(IdleStatus.BOTH_IDLE, 60);
    }

    @Override
    public void messageReceived(IoSession session, Object message) {
        // Check that we can service the request context
        HttpResponse response = new HttpResponse();
        response.setContentType("text/plain");
        response.setResponseCode(HttpResponse.HTTP_STATUS_SUCCESS);
        response.appendBody("CONNECTED");

        if (response != null) {
            session.write(response).join();
        }
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) {
        SessionLog.info(session, "Disconnecting the idle.");
        session.close();
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) {
        session.close();
    }
}
