package com.cisdi.data.HJ212.gateway;

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.cisdi.data.sdk.consts.ServiceName;
import com.cisdi.data.sdk.gateway.message.SocketMessage;
import com.cisdi.data.sdk.gateway.netty.IoSession;
import com.cisdi.data.sdk.gateway.netty.impl.AbstractIoSession;
import com.cisdi.data.sdk.service.SendService;
import com.google.common.collect.Maps;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * 
* <p>Title: Hj212IoSession.java</p>
* @author lhp
* @date 2021年05月13日
* @version 1.0
 */
public class Hj212IoSession extends AbstractIoSession implements IoSession {
	private long lastAliveTime = System.currentTimeMillis();
	private static Logger logger = LoggerFactory.getLogger(Hj212IoSession.class);
	private String deviceId = null;

	public Hj212IoSession(String deviceId) {
	    this.deviceId = deviceId;
	}

	@Override
	public void onRead(Object message) {
		int length = ((ByteBuf)message).readableBytes();
		ByteBuf inBuf = (ByteBuf)message;
		
		Hj212FrameInputVo vo = Hj212VoDecode.Decode(inBuf);
		
		if(socketGateway!= null && Boolean.TRUE.equals(socketGateway.getInstanceVo().getLogOpen())) {
			logger.info("hj212 {} 报文长度:{} vo:{} ", getChannel(), length,  JSON.toJSONString(vo));			
		}
		//发送的真正电文数据
		Map<String, Object> realDataMap = Maps.newHashMap(vo.getDataMap());
		realDataMap.put("dataTime", vo.getDataTime());
		realDataMap.put("mn", vo.getMn());
		realDataMap.put("qn", vo.getQn());
		realDataMap.put("cn", vo.getCn());
		String msgKey = String.format("%s_%s", vo.getMn(), vo.getCn());
		
		if(vo != null && serviceProvider != null && socketGateway != null) {
			SendService service = (SendService)serviceProvider.getByName(ServiceName.Send);
			
			SocketMessage socketMessage = socketGateway.buildSocketMessage();
			socketMessage.setDeviceId(deviceId);
			
			socketMessage.setData(JSON.toJSONString(realDataMap).getBytes(CRC16Util.UTF8));
			socketMessage.setMsgKey(msgKey);
			
			service.sendMessage(socketMessage);
		}else {
			logger.info("hj212收到 msgkey: {} 消息:{}",msgKey, JSON.toJSONString(realDataMap));        	
		}
		
		byte[] backBodys = Hj212VoEncoder.encode(vo.getSt(), vo.getCn(), vo.getPw(), vo.getMn());
		ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(backBodys);
		
		getChannel().writeAndFlush(wrappedBuffer);
		lastAliveTime = System.currentTimeMillis();
	}

	@Override
	public void onOpen() {
		super.onOpen();
		logger.info("建立连接，channel:{}", getChannel());
	}
	
	@Override
	public void onClose() {
		super.onClose();
	}
	
	public void close() {
		if(getChannel() != null) { 
			try {
				getChannel().close().sync();
			} catch (InterruptedException e) {
				logger.warn(e.getLocalizedMessage(), e);
			} 
		}
	}
	
	private String gwPrefixCache = null;
	
	public String gwPrefix() {
		if(gwPrefixCache != null) {
			return gwPrefixCache;
		}
		
		gwPrefixCache = "";
		if(socketGateway != null && socketGateway.getInstanceVo() != null) {
			gwPrefixCache = "网关Id:" + socketGateway.getInstanceVo().getRunId() + "连接:" + getChannel() + " ";
		}else {
			gwPrefixCache = "连接:" + getChannel() + " ";
		}
		
		return gwPrefixCache;
	}

	public long getLastAliveTime() {
		return lastAliveTime;
	}

	@Override
	public String[] getDeviceIds() {
		String cpDeviceId = deviceId;
		String[] result = new String[cpDeviceId == null ? 0 : 1];
		if(cpDeviceId != null) {
			result[0] = cpDeviceId;
		}
		return result;
	}
}