package org.kne.cloud.network.ipv6;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

import org.kne.cloud.network.NetworkPacket;
import org.kne.cloud.network.ipv6.IPv6Packet;
import org.kne.io.KNEChannels;

public class ICMPv6EchoPacket extends ICMPv6Packet {
    private static final int ECHO_HEADER_LENGTH = 4; // 标识符(2) + 序列号(2)
    
    public ICMPv6EchoPacket(boolean isRequest,int sequenceNumber,int identifier) {
        super(isRequest ? TYPE_ECHO_REQUEST : TYPE_ECHO_REPLY, 0);
        setSequenceNumber(sequenceNumber);
        setIdentifier(identifier);
    }
    
    
    /**
     * 获取标识符
     */
    public int getIdentifier() {
        return getHeader().getChar(4);
    }
    
    /**
     * 设置标识符
     */
    public void setIdentifier(int identifier) {
        getHeader().putChar(4, (char) identifier);
    }
    
    /**
     * 获取序列号
     */
    public int getSequenceNumber() {
        return getHeader().getChar(6);
    }
    
    /**
     * 设置序列号
     */
    public void setSequenceNumber(int sequenceNumber) {
        getHeader().putChar(6, (char) sequenceNumber);
    }
    
    
    /**
     * 创建Ping请求包
     */
    public static ICMPv6EchoPacket createPingRequest(int identifier, int sequenceNumber, byte[] payload) {
        ICMPv6EchoPacket packet = new ICMPv6EchoPacket(true,identifier,sequenceNumber);
        if (payload != null && payload.length > 0) {
            packet.getData().put(payload);
            packet.getData().flip();
        }
        return packet;
    }
    
    /**
     * 创建Ping回复包（基于请求包）
     */
    public static ICMPv6EchoPacket createPingReply(ICMPv6EchoPacket request) {
        ICMPv6EchoPacket reply = new ICMPv6EchoPacket(false,request.getIdentifier(),request.getSequenceNumber());
        // 复制数据
        if (request.getData() != null && request.getData().limit() > 0) {
            ByteBuffer src = request.getData().duplicate();
            src.position(0);
            reply.getData().put(src);
            reply.getData().flip();
        }
        
        return reply;
    }
    
    @Override
    public String toString() {
        String typeStr = getType() == TYPE_ECHO_REQUEST ? "Echo Request" : "Echo Reply";
        return String.format("ICMPv6 %s [ID:%d, Seq:%d, Data:%d bytes]", 
                           typeStr, getIdentifier(), getSequenceNumber(), getDataLength());
    }
}