"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var variable_1 = require("./variable");
var logger_1 = require("../../logger");
var response_1 = require("../../client/api/response");
var logger = logger_1.default('VariableManager');
var VariableManager = /** @class */ (function () {
    function VariableManager(device) {
        this.device = device;
        this._variables = {};
    }
    Object.defineProperty(VariableManager.prototype, "variableConfig", {
        get: function () {
            var variableMapping = [];
            for (var vId in this.variables) {
                var variable = this.variables[vId];
                if (variable instanceof variable_1.VariableConfig) {
                    variableMapping.push({
                        id: variable.variableId,
                        name: variable.identifier(),
                        converter: variable.converter
                    });
                }
            }
            return variableMapping;
        },
        enumerable: true,
        configurable: true
    });
    VariableManager.fromVariableConfig = function (tap, meta) {
        var manager = new VariableManager(tap);
        manager.addFromVariableConfig(meta);
        return manager;
    };
    Object.defineProperty(VariableManager.prototype, "variables", {
        // set variables(value: { [key: number]: VariableInteraction<any> }) {
        //     this._variables = value;
        // }
        get: function () {
            return this._variables;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Get variable by name
     * If it does not exist, it will throw an error
     */
    VariableManager.prototype.get = function (identifier) {
        return this.variable(identifier);
    };
    /**
     * Check is manager has variable
     * @param identifier variable identifier
     * @returns true if the variable exists
     */
    VariableManager.prototype.has = function (identifier) {
        try {
            this.variable(identifier);
            return true;
        }
        catch (err) {
            return false;
        }
    };
    /**
     * Get variable by name
     * If it does not exist, it will throw an error
     *
     * TODO remove as it's a duplicate of get()
     * @deprecated will be removed. Use {@link #get()} instead
     */
    VariableManager.prototype.variable = function (identifier) {
        // if (typeof identifier === "number"){
        //     return this.variableById(identifier as number);
        // }
        // else{
        return this.variableByName(identifier);
        // }
    };
    /**
     * Get variable by id
     * If it does not exist, it will throw an error
     */
    VariableManager.prototype.getById = function (id) {
        for (var identifier in this._variables) {
            var variable = this._variables[identifier];
            if (variable instanceof variable_1.VariableConfig) {
                if (variable.variableId == id) {
                    return this._variables[identifier];
                }
            }
        }
        throw new Error("Variable with id \"" + id + "\" does not exist");
    };
    VariableManager.prototype.getConfiguredVariables = function () {
        return __awaiter(this, void 0, void 0, function () {
            var values, variables, _a, _b, _i, variableId, variable;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.device.service.variable.getAllValues()];
                    case 1:
                        values = (_c.sent()).body();
                        variables = [];
                        _a = [];
                        for (_b in values)
                            _a.push(_b);
                        _i = 0;
                        _c.label = 2;
                    case 2:
                        if (!(_i < _a.length)) return [3 /*break*/, 5];
                        variableId = _a[_i];
                        return [4 /*yield*/, this.getConfiguredVariable(parseInt(variableId))];
                    case 3:
                        variable = _c.sent();
                        variables.push(variable);
                        _c.label = 4;
                    case 4:
                        _i++;
                        return [3 /*break*/, 2];
                    case 5: return [2 /*return*/, variables];
                }
            });
        });
    };
    /**
     * Get variable by id
     * If it does not exist, it will throw an error
     */
    VariableManager.prototype.getConfiguredVariable = function (id) {
        return __awaiter(this, void 0, void 0, function () {
            var identifier, variable, response, variableConfig;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        for (identifier in this._variables) {
                            variable = this._variables[identifier];
                            if (variable instanceof variable_1.VariableConfig) {
                                if (variable.variableId == id) {
                                    return [2 /*return*/, this._variables[identifier]];
                                }
                            }
                        }
                        return [4 /*yield*/, this.device.service.variable.getBundleId(id)];
                    case 1:
                        response = _a.sent();
                        if (!response.isSuccessful()) return [3 /*break*/, 3];
                        return [4 /*yield*/, variable_1.VariableConfig.createFromTap(id, this.device)];
                    case 2:
                        variableConfig = _a.sent();
                        this._variables[id] = variableConfig;
                        return [2 /*return*/, variableConfig];
                    case 3: throw new Error("Variable with id \"" + id + "\" is not configured or you are not authorized to access it. " + new response_1.ResponseError(response));
                }
            });
        });
    };
    VariableManager.prototype.createFromConfig = function (config) {
        return variable_1.VariableConfig.createFromConfig(config, this.device.service.variable);
    };
    VariableManager.prototype.addFromVariableConfig = function (metas) {
        var _this = this;
        metas = Array.isArray(metas) ? metas : [metas];
        metas.forEach(function (meta) {
            _this.addVariable(_this.createFromConfig(meta));
        });
        return this;
    };
    VariableManager.prototype.addFromConfig = function (config) {
        this.addFromVariableConfig(config);
        return this;
    };
    VariableManager.prototype.createFromMemoryAddress = function (identifier, memoryInfo, converter) {
        return variable_1.VariableMemory.create(identifier, memoryInfo, this.device.service.target, converter);
    };
    VariableManager.prototype.addFromMemoryAddress = function (identifier, memoryInfo, converter) {
        this.addVariable(this.createFromMemoryAddress(identifier, memoryInfo, converter));
        return this;
    };
    VariableManager.prototype.createFromModbusRegister = function (identifier, modbusOptions, converter) {
        return new variable_1.ModbusRegister(identifier, modbusOptions, this.device.service.target, converter);
    };
    VariableManager.prototype.addFromModbusRegister = function (identifier, modbusOptions, converter) {
        this.addVariable(this.createFromModbusRegister(identifier, modbusOptions, converter));
        return this;
    };
    VariableManager.prototype.addVariable = function () {
        var variables = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            variables[_i] = arguments[_i];
        }
        for (var _a = 0, variables_1 = variables; _a < variables_1.length; _a++) {
            var variable = variables_1[_a];
            var id = variable.identifier();
            logger.debug("VariableManager add variable " + id);
            if (id in this.variables) {
                logger.warn("Variable \"" + id + "\" is already registered. It will be overwritten");
            }
            this.variables[id] = variable;
        }
        return this;
    };
    /**
     * @deprecated use addFromConfig instead
     *
     * @param identifier variable identifier
     * @param configOrVariable
     */
    VariableManager.prototype.add = function (identifier, configOrVariable) {
        // if (configOrVariable instanceof VariableConfig) {
        //     this.addVariable(configOrVariable)
        // }
        // else {
        var converter;
        if (typeof configOrVariable.converter === "string") {
            converter = this.device.apiConfig.getBodyConverter(configOrVariable.converter);
        }
        else {
            converter = configOrVariable.converter;
        }
        configOrVariable.name = identifier;
        this.addFromConfig(configOrVariable);
        // }
        return this;
    };
    VariableManager.prototype.clear = function () {
        for (var id in this._variables) {
            this._variables[id].monitor().stop();
        }
        this._variables = {};
    };
    /**
     * Get variable by name
     * If it does not exist, it will throw an error
     */
    VariableManager.prototype.variableByName = function (identifier) {
        // let id = this.variableNameToId(name);
        if (!(identifier in this._variables)) {
            throw new Error("Variable \"" + identifier + "\" does not exist");
        }
        return this._variables[identifier];
    };
    return VariableManager;
}());
exports.VariableManager = VariableManager;
