import { ConditionItemObserver } from './condition-item-observer';
import { VariableValue, VariableStateEnum, VariableState } from '../../../communication';
import { BitConditonLogic } from './bit-condition-logic';
import { RelationConditionResultState } from './relation-condition-result-state';
import { Binary } from '../binary';
export class BitConditionItemObserver extends ConditionItemObserver {
    constructor(bitConditon, variableCommunicator, variableStore) {
        super(bitConditon, variableStore);
        this.bitConditon = bitConditon;
        this.variableCommunicator = variableCommunicator;
    }
    requestData(appId) {
        if (!this.bitConditon) {
            throw new Error('BitConditionModel cannot be null.');
        }
        if (this.variableName) {
            this.variableCommunicator.subscribeVariableState(this.variableName).subscribe(variableValue => {
                if (variableValue.state === VariableStateEnum.Normal) {
                    this.requestconditionEffectiveValue(this.variableCommunicator, appId);
                }
                else {
                    this.conditionEffectiveChanged.emit(new RelationConditionResultState(new VariableState(this.variableName, variableValue.state), false));
                }
            });
        }
    }
    requestconditionEffectiveValue(variableCommunicator, appId = '') {
        variableCommunicator.openVariable(this.variableName, appId).subscribe(value => {
            if (this.bitConditon.isBitwiseIndex) {
                const maxBitIndex = 31;
                this.binary = new Binary(value.value, maxBitIndex + 1);
                this.currentValue = new VariableValue(value.variableName, value.state, this.binary.convertToBinary().substr(maxBitIndex - this.bitConditon.bitIndex, 1));
            }
            else {
                this.currentValue = value;
            }
            this.isConditionEffective = this.getIsConditionEffective();
            this.conditionEffectiveChanged.emit(new RelationConditionResultState(new VariableState(this.variableName, value.state), this.isConditionEffective));
        });
    }
    getIsConditionEffective() {
        switch (this.bitConditon.bitConditionLogic) {
            case BitConditonLogic.On:
                // eslint-disable-next-line eqeqeq
                return this.currentValue.state === VariableStateEnum.DataNormal && this.currentValue.value == 1;
            case BitConditonLogic.Off:
                // eslint-disable-next-line eqeqeq
                return this.currentValue.state === VariableStateEnum.DataNormal && this.currentValue.value == 0;
            default:
                throw new Error(`Unknown BitConditonLogic : ${this.bitConditon.bitConditionLogic}.`);
        }
    }
}
