package com.platform.modules.fl.utils;

import java.nio.ByteBuffer;

import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;


/**
 * 
 * @author ktna 
 *
 */
public  class SocketAioHandler   implements ServerAioHandler
{
	
	
	/**
	 * 编码：把业务消息包编码为可以发送的ByteBuffer
	 * 总的消息结构：消息头 + 消息体
	 * 消息头结构：    4个字节，存储消息体的长度
	 * 消息体结构：   对象的json串的byte[]
	 */
	

	@Override
	public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext )
	{
		TestPacket tPacket = (TestPacket)packet;
		byte[] body = tPacket.getBody();
		int bodyLen = 0;
		if (body != null)
		{
			bodyLen = body.length;
		} 
		
		 
		//bytebuffer的总长度是 = 消息头的长度 + 消息体的长度
		int allLen = TestPacket.HEADER_LENGHT + bodyLen;
		//创建一个新的bytebuffer
		ByteBuffer buffer = ByteBuffer.allocate(allLen);
		//设置字节序
		buffer.order(groupContext.getByteOrder());

		//写入消息头----消息头的内容就是消息体的长度
		buffer.putInt(bodyLen);
		
		//写入消息体
		if (body != null)
		{
			buffer.put(body);
		}
		return buffer;
	}

 
	public Packet decode(ByteBuffer buffer, ChannelContext channelContext) throws AioDecodeException
	{
//		System.out.println( buffer.get(34));
		 
		if (buffer.get(8) == 0x21 || buffer.get(8) == 0x23)
        {
	         System.out.println("\n接收到的数据为采集信息");
	         System.out.println("\n接收到的数据为确认信息：");
	       
			
	  
	 
			int readableLength = buffer.limit() - buffer.position();
			//收到的数据组不了业务包，则返回null以告诉框架数据不够
			if (readableLength < TestPacket.HEADER_LENGHT)
			{
				return null;
			}
	
			//读取消息体的长度
			int bodyLength =  BitConverter.toInt32(buffer.array(),34);
			//数据不正确，则抛出AioDecodeException异常
			if (bodyLength < 0)
			{
				throw new AioDecodeException("bodyLength [" + bodyLength + "] is not right, remote:" + channelContext.getClientNode());
			}
			//计算本次需要的数据长度
			int neededLength = TestPacket.HEADER_LENGHT + bodyLength;
			//收到的数据是否足够组包
			int isDataEnough = readableLength - neededLength;
			// 不够消息体长度(剩下的buffe组不了消息体)
			
			if (isDataEnough < 0){
				return null;
			} else  {//组包成功
				TestPacket imPacket = new TestPacket();
				if (bodyLength > 0)
				{
					byte[] dst = new byte[bodyLength];
					System.arraycopy(buffer.array(), TestPacket.HEADER_LENGHT, dst, 0, bodyLength);
					imPacket.setBody(dst);
					buffer.position(readableLength);
				}
				return imPacket;
			}  
        }else {
        	SendPacket  sp = new SendPacket();
        	sp.setBody(buffer.array());
        	//System.out.println(buffer.);
        	System.out.println(new String(buffer.array()));
        	buffer.position(buffer.limit());
        	return sp;
        }
	}	
	 
	/** 
	 * 处理消息
	 */
 
	public void handler(Packet packet, ChannelContext channelContext) throws Exception
	{
		byte[] body = null;
		if(packet instanceof SendPacket) {
			SendPacket pack = (SendPacket) packet;
			body = pack.getBody();
		}else if(packet instanceof TestPacket) {
			TestPacket pack = (TestPacket) packet;
			body = pack.getBody();
		}
		
		if (body != null)
		{
			String str = new String(body, TestPacket.CHARSET);
			System.out.println("收到消息：" );

//			TestPacket resppacket = new TestPacket();
//			resppacket.setBody(body);
//			resppacket.setBody(("收到了你的消息，你的消息是:" + str+"！！！！！").getBytes(TestPacket.CHARSET));
			//Aio.send(channelContext, null);
		}
		return ;
	}


	   public static String getEncoding(String str) {  
	        String encode[] = new String[]{  
	                "UTF-8",  
	                "ISO-8859-1",  
	                "GB2312",  
	                "GBK",  
	                "GB18030",  
	                "Big5",  
	                "Unicode",  
	                "ASCII"  
	        };  
	        for (int i = 0; i < encode.length; i++){  
	            try {  
	                if (str.equals(new String(str.getBytes(encode[i]), encode[i]))) {  
	                    return encode[i];  
	                }  
	            } catch (Exception ex) {  
	            }  
	        }  
	          
	        return "";  
	    }  

 

 
 
}