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

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

abstract class IeAbstractQualifierOfCommand extends InformationElement {

    protected int value;

    IeAbstractQualifierOfCommand(int qualifier, boolean select) {

        if (qualifier < 0 || qualifier > 31) {
            throw new IllegalArgumentException("Qualifier is out of bound: " + qualifier);
        }

        value = qualifier << 2;

        if (select) {
            value |= 0x80;
        }

    }

    IeAbstractQualifierOfCommand(DataInputStream is) throws IOException {
        value = (is.readByte() & 0xff);
    }

    @Override
    int encode(byte[] buffer, int i) {
        buffer[i] = (byte) value;
        return 1;
    }

    /**
     * Returns true if the command selects and false if the command executes.
     *
     * @return true if the command selects and false if the command executes.
     */
    public boolean isSelect() {
        return (value & 0x80) == 0x80;
    }

    public int getQualifier() {
        return (value >> 2) & 0x1f;
    }

    @Override
    public String toString() {
        return "selected: " + isSelect() + ", qualifier: " + getQualifier();
    }

}
