/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.eactive.eai.rms.onl.server;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.eactive.eai.rms.onl.server.handler.IMessageHandler;
import com.eactive.eai.rms.onl.server.handler.TransactionSendHandler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class UdpServerHandler extends ChannelInboundHandlerAdapter {
	private static final Logger logger = Logger.getLogger(TransactionSendHandler.class);
	private final Map type2handler = new ConcurrentHashMap();
	
    @Autowired
    public void setHandlers(List<IMessageHandler> handlerList) {
        for (Iterator it = handlerList.iterator(); it.hasNext();) {
            IMessageHandler handler = (IMessageHandler) it.next();
            addMessageHandler(handler.targetClass(), handler);
        }
    }	
	
    public IMessageHandler addMessageHandler(Class type, IMessageHandler handler)
    {
        return (IMessageHandler)type2handler.put(type, handler);
    }    
    protected IMessageHandler findHandler(Class type)
    {
        return (IMessageHandler)type2handler.get(type);
    }
    
    
	
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
    	
    	IMessageHandler handler = findHandler(msg.getClass());
    	//MonitorDataVo mvo = (MonitorDataVo) msg;
        try {
        	if(handler != null){ //취약점소스 수정 2020.08.26
        		handler.messageReceived(msg);
        	}
			
		} catch (Exception e) {
			logger.error("read error.", e);
		}
    	

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("error recv "+ctx + cause,cause);
        //ctx close 하면 upd server port 가 사라져서 주석처리
        //ctx.close();
    }
}
