package com.yeejoin.amos.iec104.tcp;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.yeejoin.amos.iec104.business.param.PacketParam;
import com.yeejoin.amos.iec104.tcp.utils.ChangeUtils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class IEC104Encoder extends MessageToByteEncoder<String>{

	private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS");
	private String serviceId = "";
	public IEC104Encoder(String serviceId) {
		this.serviceId = serviceId;
	}
	
	@Override
	protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
        InetSocketAddress socket =  (InetSocketAddress) ctx.channel().remoteAddress();
		String clientIp = socket.toString();
		PacketParam param = new PacketParam();
		param.setConent(msg);
		param.setDate(sdf.format(new Date()));
		param.setType("发送");
		param.setServiceId(serviceId);
		WebSocketQueue.getInstance().add(param);
		Logger.getLogger(this.getClass()).debug("发送报文--->：" + msg.replace(" ", "") + " 到   --->" + clientIp);
		out.writeBytes(ChangeUtils.hexStringToBytes(msg.replace(" ", "")));
	}
}
