package co.dc.aptiv.mina;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.*;

import java.util.ArrayList;
import java.util.List;

public class ByteCodecFactory implements ProtocolCodecFactory {
    /**
     * 发送加密
     */
    private final ProtocolEncoderAdapter encoder;
    /**
     * 接收解密
     */
    private final ProtocolDecoderAdapter decoder;

    public ByteCodecFactory() {

        encoder = new ProtocolEncoderAdapter() {

            public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
                out.write(message);
            }
        };

        decoder = new CumulativeProtocolDecoder() {
            @Override
            protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
                List<Integer> beginSet = new ArrayList<Integer>();
                List<Integer> endSet = new ArrayList<Integer>();
                beginSet.add(0x10);
                beginSet.add(0x11);
                beginSet.add(0x23);
                beginSet.add(0x24);
                beginSet.add(0x25);
                beginSet.add(0x26);
                endSet.add(5);
                endSet.add(4);
                endSet.add(2);
                endSet.add(5);
                endSet.add(3);
                endSet.add(8);

                //有没有字节
                if (in.remaining() > 1) {
                    in.mark();
                    //byte[] l = new byte[1];
                    //in.get(l);//取开头
                    int l = in.get(0);
                    int length = -1;
                    for (int i = 0; i < beginSet.size(); i++) {
                        int currentFlag = beginSet.get(i);
                        if (l == currentFlag) {
                            //取对应的长度
                            length = endSet.get(i);
                            break;
                        }
                    }
                    //消息体不够，重新接收
                    if (in.remaining() < length) {
                        in.reset();
                        return false;
                    } else {
                        //消息体够
                        in.reset();
                        int sumlen = length;
                        byte[] packAry = new byte[sumlen];
                        in.get(packAry, 0, sumlen);
                        out.write(packAry);
                        if (in.remaining() > 0) {
                            return true;
                        }
                    }
                }
                return false;
            }
        };
    }

    public ProtocolEncoder getEncoder(IoSession session) throws Exception {
        return encoder;
    }

    public ProtocolDecoder getDecoder(IoSession session) throws Exception {
        return decoder;
    }

}
