package com.gyee.edge.protocol.iec60870.infoelement;

import java.io.DataInputStream;
import java.io.IOException;

/**
 * Represents the segment of a file as transferred by ASDUs of type F_SG_NA_1 (125).
 */
public class IeFileSegment extends InformationElement {

    private final byte[] segment;
    private final int offset;
    private final int length;

    public IeFileSegment(byte[] segment, int offset, int length) {
        this.segment = segment;
        this.offset = offset;
        this.length = length;
    }

    IeFileSegment(DataInputStream is) throws IOException {

        length = (is.readByte() & 0xff);
        segment = new byte[length];

        is.readFully(segment);
        offset = 0;
    }

    @Override
    int encode(byte[] buffer, int i) {

        buffer[i++] = (byte) length;

        System.arraycopy(segment, offset, buffer, i, length);

        return length + 1;

    }

    public byte[] getSegment() {
        return segment;
    }

    @Override
    public String toString() {
        return "File segment of length: " + length;
    }
}
