package com.nokia.sms.sgip.mt.client;

import java.util.concurrent.FutureTask;

import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.nokia.sms.sgip.RespCaller;
import com.nokia.sms.sgip.message.SgipMessage;
import com.nokia.sms.sgip.message.UnBindMessage;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@SuppressWarnings("unchecked")
public class MTClientHandler extends IoHandlerAdapter {
    public void sessionOpened(IoSession session) {
    }

    public void sessionClosed(IoSession session, IdleStatus status)
            throws Exception {
    }

    public void messageSent(IoSession session, Object object)
            throws Exception {
    }

    public void messageReceived(IoSession session, Object object)
            throws Exception {
        SgipMessage message = (SgipMessage) object;
        if (message.getHead().getCommandId() == -2147483646) {
            try {
                CloseFuture closeFuture = session.closeOnFlush();
                closeFuture.awaitUninterruptibly();
            } catch (Exception e) {
                log.error("", e);
            }
            log.info("Session closed!" + (!session.isConnected()) + ",id=" + session.getId());
            return;
        }
        String flowId = message.getHead().getStrFlowId();
        RespCaller caller = (RespCaller) session.removeAttribute("Call" + flowId);
        if (caller == null) {
            Thread.sleep(100L);
            caller = (RespCaller) session.removeAttribute("Call" + flowId);
        }
        FutureTask<Byte> task = (FutureTask<Byte>) session.removeAttribute("Future" + flowId);
        if ((caller != null) && (task != null)) {
            caller.setRespMessage(message);
            task.run();
        } else {
            log.warn("Fail to get caller." + message);
        }
    }

    public void sessionIdle(IoSession session, IdleStatus status)
            throws Exception {
        UnBindMessage unBind = new UnBindMessage();
        session.write(unBind);
        log.info("Write:" + unBind + ",id=" + session.getId());
    }
}
