package com.hmsoft.app;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.alibaba.fastjson.JSON;
import com.hmsoft.common.AppConst;
import com.hmsoft.common.MsgTypeConst;
import com.hmsoft.common.TransConst;
import com.hmsoft.common.socket.ExchangeSever;
import com.hmsoft.model.request.BizRequest;
import com.hmsoft.model.request.LoginRequest;
import com.hmsoft.model.request.LogoutRequest;
import com.hmsoft.remote.rmi.common.utils.NetUtils;
import com.hmsoft.remote.rmi.exception.RemotingException;
import com.hmsoft.remote.rmi.handler.ExchangeHandler;
import com.hmsoft.remote.rmi.model.Message;
import com.hmsoft.remote.rmi.transport.NettyChannel;

/**
 * 中转服务器.
 * @author zq
 *
 */
public class Transfer {
	
	public static ExchangeSever SERVER = null;
	public static Map<NettyChannel, String> CLI_LOGIN_MAP = new HashMap<NettyChannel, String>();//客户端登录学校
	public static ExecutorService EXECUTOR = Executors.newFixedThreadPool(3);
	
	//java -jar mtzj-transfer.jar 27.174.44.184 20880
	public static void main(String[] args) {
		if (args == null || args.length != 2) {
			args = new String[2];
			args[0] = "127.0.0.1";
			args[1] = "20880";
			//throw new IllegalArgumentException("绑定ip、端口参数输入不正确!");
		}
		SERVER = new ExchangeSever(args[0] + ":" + args[1], new ExchangeHandler() {

			@Override
			public void connected(NettyChannel channel) throws RemotingException {
				System.err.println("Transfer: connected");
			}

			@Override
			public void disconnected(NettyChannel channel) throws RemotingException {
				channel.close();
				//可能是学校端断开,也可能是命题办管理端断开
				String userName = CLI_LOGIN_MAP.remove(channel);
				if (userName != null) {
					final LogoutRequest logout = new LogoutRequest(userName);
					final String json = JSON.toJSONString(logout);
					final Message message = new Message(MsgTypeConst.TYPE_NOTIFY_CLIENT_LOGOUT, json);
					try {
						SERVER.sendToMgr(message);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void sent(NettyChannel channel, Object message) throws RemotingException {
				
			}

			@Override
			public void received(NettyChannel channel, Object message) throws RemotingException {
				
				if (message instanceof Message) {
					
					System.err.println("Transfer: received," + message);
					try {
						Message msg =  JSON.parseObject(message.toString(), Message.class);
						byte type = msg.getType();
						//管理端注册,标识通道
						if (type == MsgTypeConst.TYPE_LOGIN_RESP_TO_CLIENT) {
							
							//登录返回
							Object flag = SERVER.send(msg);
							
						} else if (type == MsgTypeConst.TYPE_HEARTBEAT) {
							//心跳验证  TODO...
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}
			}

			@Override
			public void caught(NettyChannel channel, Throwable exception) throws RemotingException {
				exception.printStackTrace();
			}
			
			@Override
			public Object reply(NettyChannel channel, Object request) throws RemotingException {
				Object ret = null;
				if (request instanceof Message) {
					final Message msg =  (Message)request;
					byte type = msg.getType();
					//登录到管理端
					if (type == MsgTypeConst.TYPE_MGE_REGISTER) {
						
						ExchangeSever.MGR_REMOTE_ADDR = NetUtils.toAddressString(channel.getRemoteAddress());
						ret = TransConst.SUCCESS;
						
					} else if (type == MsgTypeConst.TYPE_LOGIN_REQ_TO_MGE || type == MsgTypeConst.TYPE_BIZ_REQ_TO_MGE) {
						
						//ret = SERVER.sendToMgrSpecial(msg);
						ret = SERVER.sendToMgr(msg);

						if (type == MsgTypeConst.TYPE_LOGIN_REQ_TO_MGE) {
							final LoginRequest login = JSON.parseObject(msg.getMsgBody(), LoginRequest.class);
							CLI_LOGIN_MAP.put(channel, login.getUserName());
						}
						
					} else if (type == MsgTypeConst.TYPE_BIZ_RESP_TO_CLIENT) {
						
						//响应到客户端,直接转发
						final BizRequest req = JSON.parseObject(msg.getMsgBody(), BizRequest.class);
						if (req.getReqType().intValue() == AppConst.SRV_NOTIFY_SELECT
								|| req.getReqType().intValue() == AppConst.SRV_SPECIFIC_COURSE
								|| req.getReqType().intValue() == AppConst.SRV_FRESH_INIT_LIST
								|| req.getReqType().intValue() == AppConst.SRV_FINAL_PUBLISH
								|| req.getReqType().intValue() == AppConst.SRV_NOTIFY_CANCEL
								|| req.getReqType().intValue() == AppConst.SRV_PUSH_NEW_LIST
								|| req.getReqType().intValue() == AppConst.SRV_DELETE_COURSE
								|| req.getReqType().intValue() == AppConst.SRV_TRIGGER_FRESH) {
							//广播到所有学校
							ret = SERVER.sendToAllSch(msg);
						} else {
							ret = SERVER.send(msg);
						}
						
					}
				}
				return ret;
			}
		});
        synchronized (Transfer.class) {
            while (true) {
                try {
                	Transfer.class.wait();
                } catch (InterruptedException e) {
                }
            }
        }
	}
}
