var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { TapStreamReader, TapStreamWriter, } from '@iotize/tap/client/impl';
import { map } from 'rxjs/operators';
import { TapDataError } from '../tap-data-error';
export class ConverterVariableView {
    constructor(id, context) {
        this.id = id;
        this.context = context;
    }
    get converter() {
        return this.context.converter;
    }
    get valueSnapshot() {
        const lastRawValue = this.context.variable.rawValueSnaphot;
        return lastRawValue !== undefined
            ? this.decodeValue(lastRawValue)
            : undefined;
    }
    get values() {
        return this.context.variable.rawValues.pipe(map((v) => this.decodeValue(v)));
    }
    read() {
        return __awaiter(this, void 0, void 0, function* () {
            const result = yield this.context.variable.readRaw();
            return this.decodeValue(result);
        });
    }
    write(value) {
        return __awaiter(this, void 0, void 0, function* () {
            const stream = yield this.getCurrentValueStream();
            this.encodeValue(value, stream);
            stream.pos = stream.getStreamSize();
            return this.context.variable.writeRaw(stream.toBytes);
        });
    }
    getCurrentValueStream() {
        return __awaiter(this, void 0, void 0, function* () {
            let currentValue;
            if (this.context.useLastKnownValueBeforeWrite) {
                currentValue = this.context.variable.rawValueSnaphot;
            }
            else {
                currentValue = yield this.context.variable.readRaw();
            }
            if (!currentValue) {
                currentValue = new Uint8Array();
            }
            return new TapStreamWriter(currentValue);
        });
    }
    encodeValue(value, stream) {
        try {
            this.converter.encode(value, stream);
        }
        catch (err) {
            throw TapDataError.unexpectedEncodedValueError(this, value, err);
        }
    }
    decodeValue(data) {
        try {
            const stream = TapStreamReader.create(data);
            return this.converter.decode(stream);
        }
        catch (err) {
            throw TapDataError.unexpectedVariable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