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 };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { isCodeError } from '@iotize/common/error';
import { TapError } from '@iotize/tap';
import { ResultCode } from '@iotize/tap/client/api';
import { TlvBundleConverter } from '@iotize/tap/client/impl';
import { TapDataError } from '../../tap-data-error';
import { AbstractBundleDataStream, } from '../../utility/editable-data-stream';
import { createTapVariableFromConfig, TapVariable } from '../tap-variable/tap-variable';
export var TLV_BUNDLE_CONVERTER = new TlvBundleConverter();
export function createTapBundleFromConfig(tap, name, config) {
    var variables = Object.keys(config.variables)
        .reduce(function (acc, key) {
        var value = config.variables[key];
        acc[key] = createTapVariableFromConfig(tap.service.variable, key, value);
        return acc;
    }, {});
    return new TapBundle(name, {
        tap: tap,
        config: {
            id: config.id
        }
    }, variables);
}
var TapBundle = /** @class */ (function (_super) {
    __extends(TapBundle, _super);
    function TapBundle(_id, context, _variables
    // converter: EncoderDecoder<DataType, Uint8Array>
    ) {
        var _this = _super.call(this, _variables) || this;
        _this._id = _id;
        _this.context = context;
        return _this;
        // this.converter = TLV_BUNDLE_CONVERTER;
        // super(
        //     context,
        //     undefined,
        // );
    }
    Object.defineProperty(TapBundle.prototype, "id", {
        get: function () {
            return this._id;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TapBundle.prototype, "bundleId", {
        get: function () {
            return this.context.config.id;
        },
        enumerable: true,
        configurable: true
    });
    // addConfiguredVariable<T>(name: string, options: {
    //     id: number;
    //     dataType: VariableType.Data,
    //     length?: number
    // }) {
    //     if (this.hasVariable(options.id)) {
    //         throw new Error(`Alredy has variable ${name}`);
    //     }
    //     // this.context.config.variables.push({
    //     //     name,
    //     //     id: options.id
    //     // });
    //     const variable = new ConfiguredVariableDataStream<DataType>(
    //         // config as VariableConfigWithName,
    //         {
    //             tap: this.context.tap,
    //             config: {
    //                 id: options.id,
    //                 name
    //             }
    //         },
    //         getConverterFromVariableType(
    //             options.dataType,
    //             options.length || 1
    //         ),
    //         // dataStream,
    //     );
    //     this._variables.push(variable);
    // }
    TapBundle.prototype.readRawInner = function () {
        return __awaiter(this, void 0, void 0, function () {
            var variableIdMapping, streamIdMapping, _a, _b, variable, err_1;
            var e_1, _c;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _d.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.context.tap.service.bundle
                                .getValues(this.bundleId)];
                    case 1:
                        variableIdMapping = (_d.sent())
                            .body(TLV_BUNDLE_CONVERTER);
                        streamIdMapping = {};
                        try {
                            // for (const tapVariableId of vara)
                            for (_a = __values(this.variables), _b = _a.next(); !_b.done; _b = _a.next()) {
                                variable = _b.value;
                                if (variable instanceof TapVariable) {
                                    if (variable.variableId in variableIdMapping) {
                                        streamIdMapping[variable.id] = variableIdMapping[variable.variableId];
                                    }
                                    else {
                                        streamIdMapping[variable.id] = undefined;
                                        // if (!(variable.id in streamIdMapping)) {
                                        //     streamIdMapping[variable.id] = variableIdMapping[]
                                        // }
                                        // (streamIdMapping as any)[variable.id]
                                        // TODO un mapped ?
                                        // throw new Error(`${variable.id} is not mapped`)
                                    }
                                }
                            }
                        }
                        catch (e_1_1) { e_1 = { error: e_1_1 }; }
                        finally {
                            try {
                                if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
                            }
                            finally { if (e_1) throw e_1.error; }
                        }
                        return [2 /*return*/, streamIdMapping];
                    case 2:
                        err_1 = _d.sent();
                        if (isCodeError(TapError.Code.ResponseStatusError, err_1)) {
                            switch (err_1.response.status) {
                                case ResultCode.NOT_FOUND:
                                    throw TapDataError.bundleNotConfigured(this.context.config, err_1);
                            }
                        }
                        throw err_1;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    return TapBundle;
}(AbstractBundleDataStream));
export { TapBundle };
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGFwLWJ1bmRsZS5qcyIsInNvdXJjZVJvb3QiOiJuZzovL0Bpb3RpemUvdGFwL2RhdGEvIiwic291cmNlcyI6WyJsaWIvdGFyZ2V0LXZhcmlhYmxlL3RhcC1idW5kbGUvdGFwLWJ1bmRsZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFDQSxPQUFPLEVBQUUsV0FBVyxFQUFFLE1BQU0sc0JBQXNCLENBQUM7QUFDbkQsT0FBTyxFQUFPLFFBQVEsRUFBMEIsTUFBTSxhQUFhLENBQUM7QUFDcEUsT0FBTyxFQUFFLFVBQVUsRUFBRSxNQUFNLHdCQUF3QixDQUFDO0FBQ3BELE9BQU8sRUFBRSxrQkFBa0IsRUFBRSxNQUFNLHlCQUF5QixDQUFDO0FBRTdELE9BQU8sRUFBRSxZQUFZLEVBQUUsTUFBTSxzQkFBc0IsQ0FBQztBQUdwRCxPQUFPLEVBQ0gsd0JBQXdCLEdBSTNCLE1BQU0sb0NBQW9DLENBQUM7QUFFNUMsT0FBTyxFQUFFLDJCQUEyQixFQUFFLFdBQVcsRUFBRSxNQUFNLDhCQUE4QixDQUFDO0FBR3hGLE1BQU0sQ0FBQyxJQUFNLG9CQUFvQ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