"use strict";
var __extends = (this && this.__extends) || (function () {
    var 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 function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
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 default_variable_monitor_1 = require("./monitor/default-variable-monitor");
var model_1 = require("../model");
var impl_1 = require("../../client/impl");
var ArrayConverter_1 = require("../extra-converter/ArrayConverter");
function memoryInfoTotalByteLength(info) {
    return Math.ceil(memoryInfoTotalBitsLength(info) / 8);
}
function memoryInfoTotalBitsLength(info) {
    return info.length * variableFormatBitLength(info.format);
}
function variableFormatBitLength(format) {
    switch (format) {
        case model_1.VariableFormat._1_BIT:
            return 1;
        case model_1.VariableFormat._8_BITS:
            return 8;
        case model_1.VariableFormat._16_BITS:
            return 16;
        case model_1.VariableFormat._32_BITS:
            return 32;
    }
}
function defaultVariableMonitorFactory(that) {
    return default_variable_monitor_1.DefaultVariableMonitor.fromVariable(that);
}
exports.defaultVariableMonitorFactory = defaultVariableMonitorFactory;
var GenericVariableInteraction = /** @class */ (function () {
    function GenericVariableInteraction(identifier, monitorFactory) {
        if (monitorFactory === void 0) { monitorFactory = defaultVariableMonitorFactory; }
        this.monitorFactory = monitorFactory;
        this._identifier = identifier;
    }
    GenericVariableInteraction.prototype.read = function () {
        return __awaiter(this, void 0, void 0, function () {
            var rawValue;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.readRaw()];
                    case 1:
                        rawValue = _a.sent();
                        if (this.converter) {
                            return [2 /*return*/, this.converter.decode(rawValue)];
                        }
                        else {
                            return [2 /*return*/, rawValue];
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    GenericVariableInteraction.prototype.write = function (value) {
        if (this.converter) {
            var encodedValue = this.converter.encode(value);
            return this.writeRaw(encodedValue);
        }
        if (!(value instanceof Uint8Array)) {
            return Promise.reject(new Error("Illegal write argument type. Expecting bytes but found type " + typeof value));
        }
        return this.writeRaw(value);
    };
    GenericVariableInteraction.prototype.identifier = function () {
        return this._identifier;
    };
    GenericVariableInteraction.prototype.monitor = function () {
        if (!this._monitor) {
            this._monitor = this.monitorFactory(this);
        }
        return this._monitor;
    };
    return GenericVariableInteraction;
}());
exports.GenericVariableInteraction = GenericVariableInteraction;
/**
 * Dynamic variable.
 * It represents a virtual variable. It means that variable is not stored in the tap configuration.
 * We use direct memory access to read/write value
 */
var VariableMemory = /** @class */ (function (_super) {
    __extends(VariableMemory, _super);
    function VariableMemory(identifier, info, service, converter) {
        var _this = _super.call(this, identifier) || this;
        _this.converter = converter;
        _this.info = info;
        _this.service = service;
        return _this;
    }
    VariableMemory.createRaw = function (identifier, info, service) {
        return VariableMemory._create(identifier, info, service);
    };
    VariableMemory.create = function (identifier, info, service, converter) {
        return VariableMemory._create(identifier, info, service, converter);
    };
    VariableMemory.prototype.readRaw = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.readAddress(this.info)];
                    case 1:
                        response = (_a.sent());
                        response.successful();
                        return [2 /*return*/, response.rawBody()];
                }
            });
        });
    };
    VariableMemory.prototype.writeRaw = function (encodedValue) {
        return __awaiter(this, void 0, void 0, function () {
            var expectedByteSize, error;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        expectedByteSize = memoryInfoTotalByteLength(this.info);
                        if (encodedValue.length != expectedByteSize) {
                            error = new Error("Encoded value does not have the expected byte size. Expecting " + expectedByteSize + " byte(s) but given " + encodedValue.length + " byte(s)");
                            // return Promise.reject(error)
                            throw error;
                        }
                        return [4 /*yield*/, this.service.writeAddress({
                                info: this.info,
                                data: encodedValue
                            })];
                    case 1: return [2 /*return*/, (_a.sent()).successful()];
                }
            });
        });
    };
    VariableMemory._create = function (identifier, info, service, converter) {
        return new VariableMemory(identifier, info, service, converter);
    };
    return VariableMemory;
}(GenericVariableInteraction));
exports.VariableMemory = VariableMemory;
var ModbusRegister = /** @class */ (function (_super) {
    __extends(ModbusRegister, _super);
    function ModbusRegister(identifier, info, service, converter) {
        var _this = _super.call(this, identifier) || this;
        _this.converter = converter;
        _this.info = info;
        _this.service = service;
        return _this;
    }
    ModbusRegister.prototype.readRaw = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.modbusRead(this.info)];
                    case 1:
                        response = (_a.sent());
                        response.successful();
                        return [2 /*return*/, response.rawBody()];
                }
            });
        });
    };
    ModbusRegister.prototype.writeRaw = function (value) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.modbusWrite({
                            data: value,
                            options: this.info
                        })];
                    case 1: return [2 /*return*/, (_a.sent()).successful()];
                }
            });
        });
    };
    return ModbusRegister;
}(GenericVariableInteraction));
exports.ModbusRegister = ModbusRegister;
/**
 * Represents a configured TAP variable
 */
var VariableConfig = /** @class */ (function (_super) {
    __extends(VariableConfig, _super);
    function VariableConfig(config, service, variabeMonitorFactory) {
        var _this = _super.call(this, config.name || config.id.toString(), variabeMonitorFactory) || this;
        _this.service = service;
        _this.config = config;
        return _this;
    }
    VariableConfig.createFromTap = function (id, tap, configRead) {
        if (configRead === void 0) { configRead = new VariableConfigurationReader(); }
        return __awaiter(this, void 0, void 0, function () {
            var configuration, variable;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, configRead.read(id, tap)];
                    case 1:
                        configuration = _a.sent();
                        variable = new VariableConfig(configuration, tap.service.variable);
                        variable.converter = getConverterFromFormat(variable.config.type, variable.config.length);
                        return [2 /*return*/, variable];
                }
            });
        });
    };
    VariableConfig.createAllFromConfig = function (config, variableService, monitorFactory) {
        if (monitorFactory === void 0) { monitorFactory = defaultVariableMonitorFactory; }
        return config.map(function (config) {
            return VariableConfig.createFromConfig(config, variableService, monitorFactory);
        });
    };
    Object.defineProperty(VariableConfig.prototype, "variableId", {
        get: function () {
            return this.config.id;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(VariableConfig.prototype, "converter", {
        get: function () {
            return this.config.converter;
        },
        set: function (converter) {
            this.config.converter = converter;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * @deprecated use @{link createFromConfig}
     * @param identifier
     * @param variableId
     * @param service
     */
    VariableConfig.createRaw = function (identifier, variableId, service) {
        return VariableConfig._create({
            id: variableId,
            name: identifier
        }, service);
    };
    /**
     * @deprecated  use @{link createFromConfig}
     * @param identifier
     * @param variableId
     * @param service
     * @param converter
     */
    VariableConfig.create = function (identifier, variableId, service, converter) {
        return VariableConfig._create({
            id: variableId,
            name: identifier,
            converter: converter
        }, service);
    };
    VariableConfig.createFromConfig = function (config, service, variabeMonitorFactory) {
        return VariableConfig._create(config, service, variabeMonitorFactory);
    };
    VariableConfig._create = function (config, service, variabeMonitorFactory) {
        return new VariableConfig(config, service, variabeMonitorFactory);
    };
    VariableConfig.prototype.readRaw = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.getValue(this.variableId)];
                    case 1: return [2 /*return*/, (_a.sent()).rawBody()];
                }
            });
        });
    };
    VariableConfig.prototype.writeRaw = function (value) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.setValue(this.variableId, value)];
                    case 1: return [2 /*return*/, (_a.sent()).successful()];
                }
            });
        });
    };
    return VariableConfig;
}(GenericVariableInteraction));
exports.VariableConfig = VariableConfig;
var VariableConfigurationReader = /** @class */ (function () {
    function VariableConfigurationReader() {
        this.stringConverter = new impl_1.StringConverter('utf8');
    }
    VariableConfigurationReader.prototype.read = function (id, tap) {
        return __awaiter(this, void 0, void 0, function () {
            var data, _a, metaDataResponse, metaData;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = {
                            id: id
                        };
                        return [4 /*yield*/, this.readVariableType(tap, id)];
                    case 1:
                        _a.type = _b.sent();
                        return [4 /*yield*/, this.readVariableAddress(tap, id)];
                    case 2:
                        _a.address = _b.sent();
                        return [4 /*yield*/, tap.service.variable.getNumberOfElements(id)];
                    case 3:
                        // format: toEnumString((await tap.service.variable.getFormat(id)).body()!, VariableFormat),
                        _a.length = (_b.sent()).body();
                        return [4 /*yield*/, tap.service.variable.getBundleId(id)];
                    case 4:
                        data = (_a.bundleId = (_b.sent()).body(),
                            _a);
                        return [4 /*yield*/, tap.service.variable.getMetaData(id)];
                    case 5:
                        metaDataResponse = _b.sent();
                        if (metaDataResponse.isSuccessful()) {
                            metaData = this._decodeMetaData(metaDataResponse.rawBody());
                            data = __assign({}, data, metaData);
                        }
                        return [2 /*return*/, data];
                }
            });
        });
    };
    VariableConfigurationReader.prototype._decodeMetaData = function (data) {
        var dataString = this.stringConverter.decode(data);
        var meta = {};
        var parts = dataString.split(':');
        if (parts.length >= 1) {
            meta.name = parts[0];
        }
        if (parts.length >= 2) {
            meta.unit = parts[1];
        }
        return meta;
    };
    VariableConfigurationReader.prototype.readVariableAddress = function (tap, id) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, err_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 2, , 3]);
                        _a = "0x";
                        return [4 /*yield*/, tap.service.variable.getAddress(id)];
                    case 1: return [2 /*return*/, _a + (_b.sent()).body().toString(16)];
                    case 2:
                        err_1 = _b.sent();
                        return [2 /*return*/, "0x0"];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    VariableConfigurationReader.prototype.readVariableType = function (tap, id) {
        return __awaiter(this, void 0, void 0, function () {
            var err_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, tap.service.variable.getType(id)];
                    case 1: return [2 /*return*/, (_a.sent()).body()];
                    case 2:
                        err_2 = _a.sent();
                        return [2 /*return*/, model_1.VariableType.INT8]; // TODO set raw
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    return VariableConfigurationReader;
}());
exports.VariableConfigurationReader = VariableConfigurationReader;
var typeConfig = {};
typeConfig[model_1.VariableType.BOOLEAN] = {
    size: 1
};
typeConfig[model_1.VariableType.UINT8] = {
    size: 1
};
typeConfig[model_1.VariableType.UINT16] = {
    size: 2
};
typeConfig[model_1.VariableType.UINT32] = {
    size: 4
};
typeConfig[model_1.VariableType.INT8] = {
    size: 1
};
typeConfig[model_1.VariableType.INT16] = {
    size: 2
};
typeConfig[model_1.VariableType.INT32] = {
    size: 4
};
typeConfig[model_1.VariableType.FLOAT32] = {
    size: 4
};
typeConfig[model_1.VariableType.STRING] = {
    size: 1
};
/**
 * TODO
 * @param format
 * @param length
 */
function getConverterFromFormat(type, length) {
    var converter = getRawConverterFromFormat(type);
    if (converter && length > 1) {
        converter = new ArrayConverter_1.ArrayConverter(converter, {
            sizeOfItem: typeConfig[type].size
        });
    }
    return converter;
}
exports.getConverterFromFormat = getConverterFromFormat;
/**
 * TODO
 * @param format
 * @param length
 */
function getRawConverterFromFormat(type) {
    switch (type) {
        // TODO
        // case VariableType.RAW:
        //     return undefined;
        case model_1.VariableType.BOOLEAN:
            return impl_1.BooleanConverter.instanceBit0();
        case model_1.VariableType.UINT8:
            return impl_1.NumberConverter.uint8Instance();
        case model_1.VariableType.UINT16:
            return impl_1.NumberConverter.uint16Instance();
        case model_1.VariableType.UINT32:
            return impl_1.NumberConverter.uint32Instance();
        case model_1.VariableType.INT8:
            return impl_1.NumberConverter.int8Instance();
        case model_1.VariableType.INT16:
            return impl_1.NumberConverter.int16Instance();
        case model_1.VariableType.INT32:
            return impl_1.NumberConverter.int32Instance();
        case model_1.VariableType.FLOAT32:
            return impl_1.FloatConverter.instance32();
        case model_1.VariableType.STRING:
            return impl_1.StringConverter.instance();
        default:
            return undefined;
    }
}
exports.getRawConverterFromFormat = getRawConverterFromFormat;
