package com.yeejoin.amos.iec104.tcp;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.util.ObjectUtils;

import com.yeejoin.amos.iec104.business.param.PacketParam;
import com.yeejoin.amos.iec104.tcp.entity.Apdu;
import com.yeejoin.amos.iec104.tcp.utils.ChangeUtils;

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

public class IEC104Decoder  extends ByteToMessageDecoder{
	private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS");
	
	private String serviceId = "";
	public IEC104Decoder(String serviceId) {
		this.serviceId = serviceId;
	}
	
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    	in = in.markReaderIndex();
    	in = in.markWriterIndex();
    	byte[] dis = new byte[in.readableBytes()];       	
    	in.readBytes(dis);
    	in.resetReaderIndex();
    	in.resetWriterIndex();
		Logger.getLogger(this.getClass()).debug("接收报文内容： " + ChangeUtils.toHexString(dis));
		if (ObjectUtils.isEmpty(dis)) {
			in.clear();
			return;
		}

		if (in.isReadable()) {
	        int start = dis[0] & 0xff;
	        int len = dis[1] & 0xff;
	        if(start != 104 ){
	        	in.readByte();
	        	return;
	        }else if(len + 2 > in.readableBytes()){
	        	return;
	        }
			try {
				Apdu apdu = new Apdu(in);
				out.add(apdu);
			} catch (Exception e) {
				in.clear();
				e.printStackTrace();
			}		
		}
		PacketParam param = new PacketParam();
		param.setConent(ChangeUtils.toHexString(dis));
		param.setDate(sdf.format(new Date()));
		param.setType("接收");
		param.setServiceId(serviceId);
		WebSocketQueue.getInstance().add(param);
	}
}
