package org.kne.cloud.network.klalb;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Inet6Address;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;

public class ADDLINESPacket extends KLALBPacket {
	private String lines;

	private static final int HEADER_LENGTH=3;

	public String getLines() {
		return lines;
	}

	public ADDLINESPacket(String lines) {
		super(ADDLINES,HEADER_LENGTH);
		this.lines=lines;
	}

	
	public ADDLINESPacket(ByteBuffer bb) {
		super(bb,HEADER_LENGTH);
	}

	
	@Override
	public String toString() {
		return "ADDLINES "+getLines();
	}
	
	
	
	@Override
	public void writeToChannel(WritableByteChannel dto) throws IOException {
		byte[]bta=lines.getBytes(Charset.forName("UTF-8"));
		klalbHeader.putChar(1,(char) bta.length);
		super.writeToChannel(dto);
		dto.write(ByteBuffer.wrap(bta));
	}

	@Override
	public void readFromChannel(ReadableByteChannel din) throws IOException {
		super.readFromChannel(din);
		int lth=klalbHeader.getChar(1);
		byte[]b=new byte[lth];
		ByteBuffer wp= ByteBuffer.wrap(b);
				 while(wp.hasRemaining()){
		if(din.read(wp)==-1) {
			throw new EOFException();
		}
			}
		lines=new String(b, Charset.forName("UTF-8"));
	}

	@Override
	public long getTotalLength() {
		return HEADER_LENGTH+lines.getBytes(Charset.forName("UTF-8")).length;
	}

}
