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

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

/**
 * Represents a test sequence Counter (TSC) information element.
 */
public class IeTestSequenceCounter extends InformationElement {

    private static final int LOWER_BOUND = 0;
    private static final int UPPER_BOUND = 65535; // 2^16 - 1

    private final int value;

    public IeTestSequenceCounter(int value) {
        if (value < LOWER_BOUND || value > UPPER_BOUND) {
            throw new IllegalArgumentException("Value has to be in the range 0..65535");
        }

        this.value = value;
    }

    static IeTestSequenceCounter decode(DataInputStream is) throws IOException {
        return new IeTestSequenceCounter(is.readUnsignedByte() | (is.readUnsignedByte() << 8));
    }

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

        buffer[i++] = (byte) value;
        buffer[i] = (byte) (value >> 8);

        return 2;
    }

    public int getValue() {
        return value;
    }

    @Override
    public String toString() {
        return "Test sequence counter: " + getValue();
    }

}
