var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { isCodeError } from '@iotize/common/error';
import { TapError } from '@iotize/tap';
import { ResultCode } from '@iotize/tap/client/api';
import { TapDataError } from '../../tap-data-error';
import { BLANK_CONVERTER } from '../../utility/blank-converter';
import { getConverterFromVariableType } from '../../utility/type-converter-factory';
import { AbstractVariable } from '../abstract-variable-stream';
export function createTapVariableFromConfig(variableService, key, value) {
    return new TapVariable(key, {
        variableService: variableService,
        config: {
            id: value.id,
            dataType: value.dataType,
            length: value.length
        },
        converter: value.converter || (value.dataType !== undefined
            ? getConverterFromVariableType(value.dataType, value.length || 1)
            : BLANK_CONVERTER)
    });
}
var TapVariable = /** @class */ (function (_super) {
    __extends(TapVariable, _super);
    function TapVariable(
    /**
     * Variable name identifier.
     */
    id, context) {
        var _this = _super.call(this) || this;
        _this.id = id;
        _this.context = context;
        return _this;
    }
    Object.defineProperty(TapVariable.prototype, "variableId", {
        get: function () {
            return this.context.config.id;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TapVariable.prototype, "converter", {
        get: function () {
            return this.context.converter || BLANK_CONVERTER;
        },
        set: function (converter) {
            this.context.converter = converter;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TapVariable.prototype, "config", {
        get: function () {
            return this.context.config;
        },
        enumerable: true,
        configurable: true
    });
    TapVariable.prototype.readRawInner = function () {
        return __awaiter(this, void 0, void 0, function () {
            var rawData_1, err_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.context.variableService.getValue(this.context.config.id)];
                    case 1:
                        rawData_1 = (_a.sent()).body();
                        if (this.context.subIndex) {
                            rawData_1 = this.context.subIndex.reduce(function (acc, subIndex, index) {
                                acc[index] = rawData_1[subIndex];
                                return acc;
                            }, new Uint8Array(this.context.subIndex.length));
                        }
                        return [2 /*return*/, rawData_1];
                    case 2:
                        err_1 = _a.sent();
                        if (isCodeError(TapError.Code.ResponseStatusError, err_1)) {
                            switch (err_1.response.status) {
                                case ResultCode.NOT_FOUND:
                                    throw TapDataError.variableNotConfigured(this.context.config, err_1);
                            }
                        }
                        throw err_1;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    TapVariable.prototype.writeRaw = function (value) {
        return __awaiter(this, void 0, void 0, function () {
            var existingData_1, err_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 4, , 5]);
                        if (!this.context.subIndex) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.context.variableService.getValue(this.context.config.id)];
                    case 1:
                        existingData_1 = (_a.sent()).body();
                        this.context.subIndex.forEach(function (subIndex, index) {
                            existingData_1[subIndex] = value[index];
                        });
                        value = existingData_1;
                        _a.label = 2;
                    case 2: return [4 /*yield*/, this.context.variableService.setValue(this.context.config.id, value)];
                    case 3:
                        (_a.sent()).body();
                        return [3 /*break*/, 5];
                    case 4:
                        err_2 = _a.sent();
                        if (isCodeError(TapError.Code.ResponseStatusError, err_2)) {
                            switch (err_2.response.status) {
                                case ResultCode.NOT_FOUND:
                                    throw TapDataError.variableNotConfigured(this.context.config, err_2);
                            }
                        }
                        throw err_2;
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    return TapVariable;
}(AbstractVariable));
export { TapVariable };
// TODO add Sub variable data stream (IE read/write index )
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGFwLXZhcmlhYmxlLmpzIiwic291cmNlUm9vdCI6Im5nOi8vQGlvdGl6ZS90YXAvZGF0YS8iLCJz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