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 __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
import '@iotize/tap/service/impl/variable';
import '@iotize/tap/service/impl/target';
import '@iotize/tap/service/impl/interface';
import { createTapBundleFromConfig, TLV_BUNDLE_CONVERTER } from '../target-variable/tap-bundle/tap-bundle';
import { TypedDataManager } from './data-manager';
export function createTapBundlesFromConfig(tap, bundles) {
    var bundleDataStreams = {};
    for (var name_1 in bundles) {
        bundleDataStreams[name_1] = createTapBundleFromConfig(tap, name_1, bundles[name_1]);
    }
    return bundleDataStreams;
}
export function createDataManagerFromTapConfig(tap, config) {
    var bundles = config.bundles;
    return new TypedDataManager(tap, createTapBundlesFromConfig(tap, bundles));
}
export function readDataManagerTapConfigFromTap(tap, config) {
    if (config === void 0) { config = {
        bundleIdNameMap: {},
        variableIdNameMap: {}
    }; }
    return __awaiter(this, void 0, void 0, function () {
        var bundleIdNameMap, variableIdNameMap, observer, readProfileResponse, rawBundleData, profileData, bundles, variableCount, index, _a, _b, _i, variableId, variableIdInt, _c, bundleId, variableName, variableInfo, bundleName, readBundleName, endOfStringIndex;
        return __generator(this, function (_d) {
            switch (_d.label) {
                case 0:
                    bundleIdNameMap = config.bundleIdNameMap, variableIdNameMap = config.variableIdNameMap, observer = config.observer;
                    return [4 /*yield*/, tap.service.target.connect()];
                case 1:
                    (_d.sent()).successful();
                    return [4 /*yield*/, tap.service.variable.readProfile()];
                case 2:
                    readProfileResponse = _d.sent();
                    // if (!readProfileResponse.isSuccessful()) {
                    //     switch (readProfileResponse.status) {
                    //         case ResultCode.SERVICE_UNAVAILABLE:
                    //             // If service is unavailable, it probably means that target is not connected yet
                    //             (await tap.service.target.connect()).successful();
                    //             readProfileResponse = await tap.service.variable.readProfile();
                    //             break;
                    //         default:
                    //             // Throw error otherwise
                    //             readProfileResponse.successful();
                    //     }
                    // }
                    readProfileResponse.successful();
                    rawBundleData = readProfileResponse.rawBody();
                    profileData = TLV_BUNDLE_CONVERTER.decode(rawBundleData);
                    bundles = {};
                    variableCount = Object.keys(profileData).length;
                    index = 0;
                    observer === null || observer === void 0 ? void 0 : observer.next({
                        step: 'start-read-variable-config',
                        profileData: profileData,
                        progress: {
                            loaded: index,
                            total: variableCount
                        }
                    });
                    _a = [];
                    for (_b in profileData)
                        _a.push(_b);
                    _i = 0;
                    _d.label = 3;
                case 3:
                    if (!(_i < _a.length)) return [3 /*break*/, 9];
                    variableId = _a[_i];
                    variableIdInt = parseInt(variableId, 10);
                    if (isNaN(variableIdInt)) {
                        throw new Error("Invalid variable integer identifier: " + variableId);
                        return [3 /*break*/, 8];
                    }
                    observer === null || observer === void 0 ? void 0 : observer.next({
                        step: 'read-variable',
                        variableId: variableIdInt,
                        progress: {
                            loaded: index + 1,
                            total: variableCount
                        }
                    });
                    return [4 /*yield*/, readTapVariableConfigFromTap(tap, variableIdInt, variableIdNameMap ? variableIdNameMap[variableIdInt] : undefined)];
                case 4:
                    _c = _d.sent(), bundleId = _c.bundleId, variableName = _c.variableName, variableInfo = _c.config;
                    bundleName = void 0;
                    if (!(bundleIdNameMap && (bundleId in bundleIdNameMap))) return [3 /*break*/, 5];
                    bundleName = bundleIdNameMap[bundleId];
                    return [3 /*break*/, 7];
                case 5: return [4 /*yield*/, tap.service.bundle.getName(bundleId)];
                case 6:
                    readBundleName = (_d.sent()).body();
                    endOfStringIndex = readBundleName.indexOf('\u0000');
                    if (endOfStringIndex >= 0) {
                        readBundleName = readBundleName.substr(0, endOfStringIndex);
                    }
                    if (!readBundleName) {
                        bundleName = bundleId;
                    }
                    else {
                        bundleName = readBundleName;
                    }
                    _d.label = 7;
                case 7:
                    if (!(bundleName in bundles)) {
                        bundles[bundleName] = {
                            id: bundleId,
                            variables: {}
                        };
                    }
                    else {
                        // TODO what to do when duplicated bundle name ? 
                    }
                    bundles[bundleName].variables[variableName] = variableInfo;
                    index++;
                    _d.label = 8;
                case 8:
                    _i++;
                    return [3 /*break*/, 3];
                case 9:
                    observer === null || observer === void 0 ? void 0 : observer.next({
                        step: 'end-read-variable-config',
                        progress: {
                            loaded: variableCount,
                            total: variableCount
                        }
                    });
                    return [2 /*return*/, bundles];
            }
        });
    });
}
export function readTapVariableConfigFromTap(tap, variableId, variableName) {
    return __awaiter(this, void 0, void 0, function () {
        var _a, typeResponse, bundleIdResponse, lengthResponse, metaResponse, bundleId, variableType, length, dataType, meta;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, tap.service.interface.executeMultipleCalls([
                        tap.service.variable.getTypeCall(variableId),
                        tap.service.variable.getBundleIdCall(variableId),
                        tap.service.variable.getNumberOfElementsCall(variableId),
                        tap.service.variable.getMetaCall(variableId)
                    ])];
                case 1:
                    _a = __read.apply(void 0, [(_b.sent()), 4]), typeResponse = _a[0], bundleIdResponse = _a[1], lengthResponse = _a[2], metaResponse = _a[3];
                    bundleId = bundleIdResponse.body();
                    variableType = typeResponse.body();
                    length = lengthResponse.body();
                    dataType = variableType.data;
                    if (!variableName) {
                        meta = metaResponse.body();
                        variableName = meta.name || variableId.toString();
                    }
                    return [2 /*return*/, {
                            bundleId: bundleId,
                            variableName: variableName,
                            config: {
                                id: variableId,
                                dataType: dataType,
                                length: length
                            }
                        }];
            }
        });
    });
}
//# sourceMappingURL=data:application/json;base64, 