package org.kne.cloud.network.ipv6;

import java.io.IOException;
import java.io.StreamCorruptedException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.List;

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

public class ICMPv6PostcardPacket extends ICMPv6Packet {
	private List<PostcardEntry> postcards=new ArrayList<>();
	protected ICMPv6PostcardPacket(ByteBuffer header) {
		super(header, false);
	}
	
	public ICMPv6PostcardPacket(int code) {
		super(ICMPv6Packet.TYPE_POSTCARD, code, false);
	}

	public ICMPv6PostcardPacket() {
		this(0);
	}
	
	public List<PostcardEntry> getPostcards() {
		return postcards;
	}

	@Override
	public long getTotalLength() {
		return ICMPv6Packet.ICMPv6_HEADER_LENGTH+postcards.size()*PostcardEntry.POSTCARD_ENTRY_SIZE;
	}

	@Override
	public void writeToChannel(WritableByteChannel dto) throws IOException {
		super.writeToChannel(dto);
		for(PostcardEntry postcard:postcards) {
			postcard.writeToChannel(dto);
		}
	}

	@Override
	public String toString() {
		return "ICMPv6PostcardPacket [postcards=" + postcards + ", getTotalLength()=" + getTotalLength() + "]";
	}

	@Override
	public void readFromChannel(ReadableByteChannel din, long length) throws IOException {
		super.readFromChannel(din, length);
		postcards.clear();
		int count= (int) ((length-ICMPv6Packet.ICMPv6_HEADER_LENGTH)/PostcardEntry.POSTCARD_ENTRY_SIZE);
		for(int i=0;i<count;i++) {
			PostcardEntry pe=new PostcardEntry();
			pe.readFromChannel(din);
			postcards.add(pe);
		}
	}
	
}
