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 { ResultCode } from '@iotize/tap/client/api';
import '@iotize/tap/service/impl/target';
import '@iotize/tap/service/impl/variable';
import '@iotize/tap/service/impl/interface';
import { Observable } from 'rxjs';
import { share } from 'rxjs/operators';
import { DBIOT_VARIABLE_CONFIG_CONVERTER } from './constants';
/**
 * Create shared observable that read DBIOT configuration from tap
 * @param tap
 * @param maxVar
 * @returns
 */
export function createReadDBIOTConfigurationFromTapObservable(tap, maxVar) {
    const obs = new Observable((emitter) => {
        let stopLoop = false;
        const progressEvent = {
            type: 'start',
            data: {
                total: maxVar,
            },
        };
        emitter.next(progressEvent);
        (() => __awaiter(this, void 0, void 0, function* () {
            try {
                const targetProtocol = (yield tap.service.target.getProtocol()).body();
                const variables = [];
                const progressEvent = {
                    type: 'progress',
                    data: {
                        current: 0,
                        total: maxVar,
                    },
                };
                emitter.next(progressEvent);
                for (let variableId = 0; variableId < maxVar && !stopLoop; variableId++) {
                    const variableConfig = yield readTapVariableConfigWithDBIOTuration(tap, variableId);
                    if (variableConfig) {
                        variables.push(variableConfig);
                    }
                    const progressEvent = {
                        type: 'progress',
                        data: {
                            current: variableId + 1,
                            total: maxVar,
                            variable: variableConfig,
                        },
                    };
                    emitter.next(progressEvent);
                }
                if (!stopLoop) {
                    const result = {
                        type: 'complete',
                        data: {
                            bundles: [],
                            variables,
                            targetProtocol,
                        },
                    };
                    emitter.next(result);
                }
                emitter.complete();
            }
            catch (err) {
                emitter.error(err);
            }
        }))();
        return () => {
            stopLoop = true;
        };
    });
    return obs.pipe(share());
}
function readTapVariableConfigWithDBIOTuration(tap, id) {
    return __awaiter(this, void 0, void 0, function* () {
        const [lengthRes, typeRes, bundleIdRes] = yield tap.service.interface.executeMultipleCalls([
            tap.service.variable.getNumberOfElementsCall(id),
            tap.service.variable.getTypeCall(id),
            tap.service.variable.getBundleIdCall(id),
        ]);
        if (!lengthRes.isSuccessful()) {
            if (lengthRes.codeRet() === ResultCode.NOT_FOUND) {
                return undefined;
            }
        }
        const length = lengthRes.body();
        let dbiot = undefined;
        if (length > 0) {
            const rawMetaResponse = yield tap.service.variable.getRawMeta(id);
            const rawData = rawMetaResponse.body();
            if (rawData.length > 0) {
                try {
                    dbiot = DBIOT_VARIABLE_CONFIG_CONVERTER.decode(rawData);
                }
                catch (err) {
                    // Ignore if dbiot variable is not set property
                    console.warn(`Cannot parse dbiot info for variable "${id}"`, err);
                    return;
                }
            }
        }
        return {
            id,
            bundleId: bundleIdRes.body(),
            length,
            type: typeRes.body(),
            dbiot,
        };
    });
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbGl0eS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uLy4uL2V4dHJhL2RiaW90L3NyYy9saWIvdXRpbGl0eS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7QUFDQSxPQUFPLEVBQUUsVUFBVSxFQUFFLE1BQU0sd0JBQXdCLENBQUM7QUFDcEQsT0FBTyxpQ0FBaUMsQ0FBQztBQUN6QyxPQUFPLG1DQUFtQyxDQUFDO0FBQzNDLE9BQU8sb0NBQW9DLENBQUM7QUFDNUMsT0FBTyxFQUFFLFVBQVUsRUFBRSxNQUFNLE1BQU0sQ0FBQztBQUNsQyxPQUFPLEVBQUUsS0FBSyxFQUFFLE1BQU0sZ0JBQWdCLENBQUM7QUFDdkMsT0FBTyxFQUFFLCtCQUErQixFQUFF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