import { asciiStringToByteBuffer, bufferToHexString, hexStringToBuffer, } from '@iotize/common/byte-converter';
import { KaitaiStreamWriter } from '@iotize/common/byte-stream';
import { DotAccessor } from '@iotize/common/data-accessor';
import { HostProtocol, SpecialFeature } from '@iotize/tap';
import { ADMIN_USER, ANONYMOUS_USER, isSpecialUser, } from '@iotize/tap/configurator';
import { SecurityOptionsConverter, SerialSettings, SlaveServerRawConfig, tapnpassConverters, TapnpassProtocolConfigurationConverter, TargetCanProtocolConfiguration, VariableType, } from '@iotize/tap/service/all';
import { converters } from '@iotize/tap/service/core';
import { parse } from 'fast-xml-parser';
import { IoTizeStudioError } from '../errors';
import { toEnumType } from '../util';
import { LowPowerOptimizationLevelMapping, NetworkModeMapping, NFCParingModeMapping, NFC_CONNECTION_PRIORITY_MAPPING, S3P_CONFIG_MODE_MAPPING, TargetProtocolMapping, WIFI_KEY_VISIBILITY_MAPPING, WIFI_PROTOCOL_MAPPING, WIFI_SSID_VISIBILITY_MAPPING, } from './mapping';
import { convertToVariableType, fromMapping, isTruthy } from './utility';
export function xmlToJson(xml) {
    return parse(xml, {
        attributeNamePrefix: '',
        ignoreAttributes: false,
    });
}
export function convertIoTizeStudioConfigToTapConfig(fileContent) {
    // console.log('File content', fileContent);
    const config = new IoTizeStudioToTapConfigConverter().convert(new DotAccessor(xmlToJson(fileContent)));
    return config;
}
function isHexString(input) {
    if (typeof input !== 'string') {
        return false;
    }
    return input.match(/^(0x)?([a-fA-F0-9])*$/);
}
export function decodeInitialVariableValue(value) {
    const values = value
        .split(';')
        .reduce((prev, v) => {
        if (v.length === 0) {
            return prev;
        }
        if (v.startsWith('0x')) {
            prev.push(v);
        }
        else {
            prev.push(parseFloat(v));
        }
        return prev;
    }, []);
    return values.length > 0
        ? values.length === 1
            ? values[0]
            : values
        : undefined;
}
function addNodeValueIfExist(data, config, mapping, method = 'string') {
    Object.entries(mapping).forEach(([iotzName, apiName]) => {
        var _a;
        const value = (_a = data
            .get(iotzName, undefined)) === null || _a === void 0 ? void 0 : _a.value('Name', method, undefined);
        if (value) {
            config[apiName] = value;
        }
    });
}
function addAttributeIfExist(data, config, iotzName, apiName, method) {
    const value = data === null || data === void 0 ? void 0 : data.value(iotzName, method, undefined);
    if (value !== undefined && value !== '') {
        config[apiName] = value;
    }
}
function addAttributesIfExists(data, config, mapping, method = 'string') {
    Object.entries(mapping).forEach(([iotzName, apiName]) => {
        addAttributeIfExist(data, config, iotzName, apiName, method);
    });
}
/**
 * Convert an IoTize studio configuration file to TapConfiguratorConfig
 */
export class IoTizeStudioToTapConfigConverter {
    constructor(options = {
        strict: false,
    }, host) {
        this.options = options;
        this.host = host;
        /**
         * Errors reported during convertion when strict mode is disabled
         */
        this.warnings = [];
        this.modbusSerialConfigConverter = new TapnpassProtocolConfigurationConverter();
    }
    convert(root) {
        const config = root.get('IOTizeConfiguration');
        const appConfigNode = config.get('IOTizeApp');
        const wifiConfigNode = appConfigNode.get('WIFI_Info', undefined);
        const bundles = config.list('IOTizeBundle', []);
        const profiles = config.list('IOTizeProfile', []);
        const versionString = config.value('Version', 'string', '1.0.0');
        const result = {
            version: versionString,
            application: this.readApplicationConfig(appConfigNode),
            data: {
                bundles: this.readBundlesConfig(bundles),
                profiles: this.readProfilesConfig(profiles),
            },
            cloud: this.readCloudConfig(appConfigNode),
            jvm: this.readJvmConfig(config),
            wireless: {
                options: this.readWirelessOptionsConfig(appConfigNode),
                protocols: {
                    wifi: this.readWifiConfig(wifiConfigNode),
                    mqtt: this.readMqttConfig(wifiConfigNode),
                    ble: this.readBleConfig(appConfigNode),
                    lora: this.readLoraConfig(appConfigNode),
                    nfc: this.readNfcConfig(appConfigNode),
                },
            },
            tap: this.readTapConfig(appConfigNode),
            target: this.readTargetConfig(appConfigNode),
        };
        const slaveServerConfig = this.readSlaveServerConfig(appConfigNode);
        if (slaveServerConfig) {
            result.slaveServer = slaveServerConfig;
        }
        const ethernet = this.readEthernetConfig(appConfigNode);
        if (ethernet) {
            result.ports = {
                ethernet,
            };
        }
        if (this.warnings.length > 0) {
            // TODO
        }
        return result;
    }
    reportError(error, message = error.message) {
        if (this.options.strict) {
            throw error;
        }
        this.warnings.push({
            error,
            message,
        });
    }
    readSlaveServerConfig(appConfig) {
        if (!appConfig) {
            return undefined;
        }
        const channel = appConfig.value('MBS_Com_Channel', 'number', 0);
        switch (channel) {
            case SlaveServerRawConfig.Channel.CAN:
                return {
                    type: 'CAN',
                    config: this.readCanProtocolConfig(appConfig),
                };
            case SlaveServerRawConfig.Channel.MODBUS_RTU:
                const targetProtocolConfDataLen = appConfig.value('MBSProtocolConfDataLen', 'number', 0);
                let protocolData = hexStringToBuffer(appConfig.value('MBSProtocolConfData', 'string', ''));
                return {
                    type: 'MODBUS_RTU',
                    config: this._protocolDataToJsonConfig(protocolData, targetProtocolConfDataLen),
                };
            case SlaveServerRawConfig.Channel.MODBUS_TCP:
                return {
                    type: 'MODBUS_TCP',
                    config: {
                        port: appConfig.value('MBS_ModbusTCP_Port', 'number', 502),
                        firstRegisterAddress: appConfig.value('MBS_ModbusTCP_Addr0', 'number', 0),
                    },
                };
            case SlaveServerRawConfig.Channel.SPI:
                return {
                    type: 'SPI',
                };
            case SlaveServerRawConfig.Channel.DISABLED:
                return undefined;
            default:
                throw new Error('Invalid config'); // TODO proper error
        }
    }
    readMqttConfig(cloudServicesConfig) {
        var _a;
        if (!cloudServicesConfig) {
            return undefined;
        }
        const config = {};
        addNodeValueIfExist(cloudServicesConfig, config, {
            CloudHostName: 'brokerHostname',
            CloudServiceName: 'brokerPort',
            CloudMQTT_UID: 'password',
            GUI_DevNetkey: 'netKey',
            GUI_DevMQTT_ClientID: 'clientId',
            CloudMQTT_USERNAME: 'username',
        });
        const brokerCertificate = this.readFileContentAsHexString((_a = cloudServicesConfig
            .get('AWSRootCertificate', undefined)) === null || _a === void 0 ? void 0 : _a.value('Name', 'string', undefined));
        if (brokerCertificate) {
            config.brokerCertificate = brokerCertificate;
        }
        return config;
    }
    readLoraConfig(appConfigNode) {
        return {
            config: undefined,
            ids: undefined,
        };
    }
    readBleConfig(appConfigNode) {
        return {};
    }
    readNfcConfig(appConfigNode) {
        return {
            autoLogProfileId: appConfigNode.value('NFCLogin', 'number', undefined),
            connectionPriority: fromMapping(appConfigNode, 'NFCInterruptionLock', NFC_CONNECTION_PRIORITY_MAPPING, undefined),
        };
    }
    readWifiConfig(wifiConfigNode) {
        if (!wifiConfigNode) {
            return undefined;
        }
        const mode = fromMapping(wifiConfigNode, 'Network', NetworkModeMapping, 'P2P');
        const isAP = mode === 'PEER_TO_PEER';
        const config = {
            mode,
        };
        addAttributeIfExist(wifiConfigNode, config, 'ModuleIPMask', 'mask', 'string');
        addAttributeIfExist(wifiConfigNode, config, 'ModuleIPGateway', 'gatewayIp', 'string');
        addAttributeIfExist(wifiConfigNode, config, 'ModuleIPAddress', 'ip', 'string');
        addAttributeIfExist(wifiConfigNode, config, 'Wifi_TxLevel', 'txPower', 'number');
        const keyVisibility = fromMapping(wifiConfigNode, 'Wifi_WEPKey_Hidden', WIFI_KEY_VISIBILITY_MAPPING, undefined);
        if (keyVisibility !== undefined) {
            config.keyVisibility = keyVisibility;
        }
        const protocol = fromMapping(wifiConfigNode, 'Wifi_Protocol', WIFI_PROTOCOL_MAPPING, undefined);
        if (protocol) {
            config.protocol = protocol;
        }
        addAttributeIfExist(wifiConfigNode, config, 'Wifi_Region', 'countryCode', 'number');
        const ssidVisibility = fromMapping(wifiConfigNode, 'Wifi_SSID_Hidden', WIFI_SSID_VISIBILITY_MAPPING, undefined);
        if (ssidVisibility) {
            config.ssidVisibility = ssidVisibility;
        }
        addAttributeIfExist(wifiConfigNode, config, isAP ? 'Module_AP_SSID' : 'ModuleSSID', 'ssid', 'string');
        addAttributeIfExist(wifiConfigNode, config, isAP ? 'Module_AP_WEPKey' : 'ModuleWEPKey', 'key', 'string');
        return config;
    }
    toAuthorizedHostProtocols(value) {
        if (!value || value === 'ALL' || value === 'FFFF') {
            return undefined;
        }
        if (isHexString(value)) {
            const encodedValue = hexStringToBuffer(value);
            return converters.hostProtocolArray.decode(encodedValue).map((p) => {
                return HostProtocol[p];
            });
        }
        else {
            return value.split(',').reduce((prev, value) => {
                value = value.trim();
                try {
                    // TODO check it's a read HostProtocolConfig...
                    prev.push(value); //stringToEnum<HostProtocolConfig>(HostProtocolConfig, value));
                }
                catch (err) {
                    this.reportError(err);
                }
                return prev;
            }, []);
        }
    }
    readAuthorizedHostProtocols(appConfigNode) {
        let availableHostProtocols = undefined;
        const hostProtocolString = appConfigNode.value('HostProtocol', 'string', undefined);
        try {
            availableHostProtocols =
                this.toAuthorizedHostProtocols(hostProtocolString);
        }
        catch (err) {
            this.reportError(err, `Cannot convert HostProtocol value "${hostProtocolString}"`);
        }
        return availableHostProtocols && availableHostProtocols.length > 0
            ? availableHostProtocols
            : undefined;
    }
    readWirelessOptionsConfig(appConfigNode) {
        const wirelessOptionsConfig = {
            inactivityTimeout: appConfigNode.value('LowPowerHostTimeout', 'number', 0),
        };
        const authorizedProtocols = this.readAuthorizedHostProtocols(appConfigNode);
        if (authorizedProtocols) {
            wirelessOptionsConfig.authorizedProtocols = authorizedProtocols;
        }
        const nfcPairingMode = fromMapping(appConfigNode, 'NFCPairingMandatory', NFCParingModeMapping, undefined);
        const blePairing = appConfigNode.value('BLEPairingRequest', 'boolean', undefined);
        if (nfcPairingMode !== undefined || blePairing !== undefined) {
            wirelessOptionsConfig.pairing = {
                blePairing,
                nfcPairingMode,
            };
        }
        return wirelessOptionsConfig;
    }
    readJvmConfig(config) {
        const appConfigNode = config.get('IOTizeApp');
        const envNode = config.get('GUI_Environment', undefined);
        const bcbFile = appConfigNode.value('JVM_Custom_Code', 'string', undefined);
        const useJvm = envNode === null || envNode === void 0 ? void 0 : envNode.value('UseInternalJVM', 'boolean', false);
        if (!useJvm) {
            return undefined;
        }
        return {
            code: bcbFile ? this.readFileContentAsHexString(bcbFile) : undefined,
            // profileId: appConfigNode.value('TODO', 'number', undefined) // TODO
        };
    }
    readEthernetConfig(accessor) {
        const data = {};
        addAttributesIfExists(accessor, data, {
            EthernetIPAddress: 'ip',
            EthernetIPGateway: 'gatewayIp',
            EthernetIPMask: 'ipMask',
        });
        if (Object.keys(data).length === 0) {
            return undefined;
        }
        return data;
    }
    readFileContentAsHexString(path) {
        if (!path) {
            return undefined;
        }
        if (!this.host) {
            this.reportError(new Error(`External file reference "${path}" cannot be resolved`));
        }
        if (this.host) {
            try {
                const fileContent = this.host.getFileContent(path);
                return '0x' + bufferToHexString(fileContent);
            }
            catch (err) {
                this.reportError(err);
            }
        }
        return undefined;
    }
    readCloudConfig(appConfigNode) {
        const cloudService = appConfigNode.get('CloudServices', undefined);
        // TODO cloud services
        // if (cloudService?.has('CloudMQTT_UID')) {
        //     let url = '';
        //     const cloudHostName = cloudService.get('CloudHostName', undefined);
        //     const cloudServiceName = cloudService.get('CloudServiceName', undefined);
        //     if (cloudHostName) {
        //         url = `mqtt://${cloudHostName.value('Name', 'string', '')}:${cloudServiceName?.value('Name', 'string', '') || ''}`;
        //     }
        //     // cloud = {
        //     //     // password: cloudService
        //     //     //     .get('CloudMQTT_UID', undefined)
        //     //     //     ?.value('Name', 'string', '') || '',
        //     //     uploadPeriod: ,
        //     //     url
        //     // };
        // }
        const wifiNode = appConfigNode.get('WIFI_Info', undefined);
        const cloudConfig = {};
        const dataLogConfig = {};
        if (wifiNode) {
            addAttributesIfExists(wifiNode, dataLogConfig, {
                Cloud_Publish_Topic: 'mqttPublishTopic',
                Cloud_Subscribe_Topic: 'mqttSubscribeTopic',
            });
        }
        if (cloudService) {
            addAttributesIfExists(cloudService, dataLogConfig, {
                CloudMqttPeriod: 'uploadPeriod',
            }, 'number');
        }
        if (Object.keys(dataLogConfig).length > 0) {
            cloudConfig.dataLog = dataLogConfig;
        }
        if (Object.keys(cloudConfig).length > 0) {
            return cloudConfig;
        }
        else {
            return undefined;
        }
    }
    readApplicationConfig(appConfigNode) {
        const appPath = appConfigNode.has('GUI_Path')
            ? appConfigNode.value('GUI_Path', 'string', '')
            : appConfigNode.value('Path', 'string', '');
        // const appPathInfo = this.appPathConverter.decode(appPath);
        const config = {
            name: appConfigNode.value('Name', 'string', 'Tap'),
            universalLink: appConfigNode.value('WebLink', 'string', ''),
            uri: appPath,
        };
        const productCode = appConfigNode.value('ProductCode', 'string', undefined);
        if (productCode !== undefined) {
            config.productCode = productCode;
        }
        const additionalData = appConfigNode.value('Data', 'string', undefined);
        if (additionalData !== undefined) {
            config.data = `0x${bufferToHexString(asciiStringToByteBuffer(additionalData))}`;
        }
        return config;
    }
    readTapConfig(appConfigNode) {
        var _a, _b;
        const lockSettingsEncoded = appConfigNode.value('InterfaceLock', 'number', 0);
        const lockOptions = new SecurityOptionsConverter().decode(Uint8Array.from([0, lockSettingsEncoded])); // TODO pad instead
        const tapOptions = {
            security: lockOptions,
            powerOptimization: fromMapping(appConfigNode, 'LowPowerLevel', LowPowerOptimizationLevelMapping, undefined),
            scram: {
                hashIteration: appConfigNode.value('Scram_Hash_It', 'number', 5000),
            },
            certificate: {
                publicKey: this.readFileContentAsHexString((_a = appConfigNode
                    .get('DeviceCertificate', undefined)) === null || _a === void 0 ? void 0 : _a.value('Name', 'string', undefined)),
                privateKey: this.readFileContentAsHexString((_b = appConfigNode
                    .get('DevicePrivateKey', undefined)) === null || _b === void 0 ? void 0 : _b.value('Name', 'string', undefined)),
            },
        };
        const timeZoneStr = appConfigNode.value('TimeZoneStr', 'string', undefined);
        const ntpServer = appConfigNode.value('NTP_URL', 'string', undefined);
        if (timeZoneStr || ntpServer) {
            tapOptions.time = {
                zone: timeZoneStr,
                ntpServer,
            };
        }
        return tapOptions;
    }
    readTapTimeConfig(appConfigNode) {
        const zone = appConfigNode.value('TimeZoneStr', 'string', undefined);
        const ntpServer = appConfigNode.value('NTP_URL', 'string', undefined);
        if (zone || ntpServer) {
            return {
                zone,
                ntpServer,
            };
        }
        return undefined;
    }
    readTargetConfig(appConfig) {
        const firmwareVersion = appConfig.value('Firmware', 'string', undefined);
        if (appConfig.value('GUI_TargetType', 'string', '0') === '1') {
            return {
                type: 'TAPNPASS',
                protocol: {
                    config: this.readTapnpassTargetProtocolConfig(appConfig),
                },
                firmwareVersion,
            };
        }
        else {
            const protocol = this.readMCUTargetProtocol(appConfig);
            if (!protocol) {
                return undefined;
            }
            return {
                type: 'MCU',
                protocol,
                firmwareVersion,
            };
        }
        // if (appConfig.has('USB_Aliases')) {
        //   data.type = "TAPNPASS";
        //   (data as TapNPassTargetConfig).usb = this._convertUsbData(appConfig);
        // }
    }
    readTargetProtocol(appConfig) {
        // const targetProtocolString = appConfig.value('TargetProtocol', 'string', 'SWD');
        return fromMapping(appConfig, 'TargetProtocol', TargetProtocolMapping, 'NONE');
    }
    readTapnpassTargetProtocol(appConfig) {
        const targetProtocol = this.readTargetProtocol(appConfig);
        switch (targetProtocol) {
            case 'SERIAL':
                return {
                    type: 'SERIAL',
                    config: this.readTapnpassTargetProtocolConfig(appConfig),
                };
            case 'MODBUS':
                return {
                    type: 'MODBUS',
                    config: this.readTapnpassTargetProtocolConfig(appConfig),
                };
            default:
                throw new Error(`Illegal target protocol "${targetProtocol === null || targetProtocol === void 0 ? void 0 : targetProtocol.toString()}" for TapNPass target type.`);
        }
    }
    readTapnpassTargetProtocolConfig(appConfig) {
        const targetProtocolConfDataLen = appConfig.value('TargetProtocolConfDataLen', 'number', 0);
        const protocolData = hexStringToBuffer(appConfig.value('TargetProtocolConfData', 'string', ''));
        return this._protocolDataToJsonConfig(protocolData, targetProtocolConfDataLen);
    }
    readMCUTargetProtocol(appConfig) {
        const targetProtocol = this.readTargetProtocol(appConfig);
        switch (targetProtocol) {
            case 'SWD':
                return {
                    type: targetProtocol,
                };
            case 'CUSTOM':
                return {
                    type: 'CUSTOM',
                    // config: '0xTODO'
                };
            case 'MODBUS':
                return {
                    type: 'MODBUS',
                    config: this.readModbusProtocolConfig(appConfig),
                };
            case 'S3P':
                return {
                    type: 'S3P',
                    config: this.readS3PProtocolConfig(appConfig),
                };
            case 'SERIAL':
                return {
                    type: 'SERIAL',
                    config: this.readSerialProtocolConfig(appConfig),
                };
            case 'NONE':
                return undefined;
            case 'DIRECT_IO':
                return {
                    type: 'DIRECT_IO',
                };
            case 'CAN':
                return {
                    type: 'CAN',
                    config: this.readCanProtocolConfig(appConfig),
                };
            case 'MODBUS_TCP':
                return {
                    type: 'MODBUS_TCP',
                    config: this.readModbusTcpProtocolConfig(appConfig),
                };
            case 'JTAG':
            default:
                throw new Error(`Target protocol convertion from "${targetProtocol === null || targetProtocol === void 0 ? void 0 : targetProtocol.toString()}" is not supported yet.`);
        }
    }
    readSerialProtocolConfig(appConfig) {
        const config = this.readModbusProtocolConfig(appConfig);
        if (!config) {
            return undefined;
        }
        return config === null || config === void 0 ? void 0 : config.serial;
    }
    readS3PProtocolConfig(appConfig) {
        return {
            mode: fromMapping(appConfig, 'S3Pmode', S3P_CONFIG_MODE_MAPPING) || 'EMULATION',
            delay: appConfig.value('S3PDelay', 'number', 1),
        };
    }
    /**
     * CAN_Freqkbps="0" CAN_Mode="1" CAN_Filter="1" CAN_Code="305419896" CAN_Mask="2596069104"
     * @param appConfig
     * @returns
     */
    readCanProtocolConfig(appConfig) {
        return {
            frequency: appConfig.value('CAN_Freqkbps', 'number', 25),
            mode: fromMapping(appConfig, 'CAN_Mode', TargetCanProtocolConfiguration.Mode) || 'NORMAL',
            filter: fromMapping(appConfig, 'CAN_Filter', TargetCanProtocolConfiguration.Filter) || 'SINGLE',
            code: toHexNumberConfig(appConfig.value('CAN_Code', 'number', 0x0)),
            mask: toHexNumberConfig(appConfig.value('CAN_Mask', 'number', 0xffffffff)),
        };
    }
    readModbusTcpProtocolConfig(node) {
        const data = {
            modbus: {},
        };
        addAttributesIfExists(node, data['modbus'], {
            ModbusTCPDefSlaveAddr: 'defaultSlaveAddress',
        });
        addAttributesIfExists(node, data['modbus'], {
            ModbusTCPAddr0: 'firstRegisterAddress',
            ModbusTCPPort: 'port',
            ModbusTCPTimeout: 'timeout',
        }, 'number');
        if (Object.keys(data).length === 0) {
            return undefined;
        }
        return data;
    }
    readModbusProtocolConfig(appConfig) {
        const config = this.readTapnpassTargetProtocolConfig(appConfig);
        const partialSerial = config.serial;
        delete partialSerial.identification;
        delete partialSerial.physicalPort;
        delete partialSerial.hardwareFlowControl;
        delete partialSerial.ledStatus;
        return {
            modbus: config.modbus,
            serial: config.serial,
        };
    }
    toEnumKey(value, mapping
    // , defaultValue: (keyof MappingType)
    ) {
        // if (value === undefined) {
        //     return defaultValue;
        // }
        if (!(value in mapping)) {
            this.reportError(new Error(`Cannot find corresponding key for value "${value}". Available keys: ${Object.keys(mapping).join(', ')}`));
        }
        return mapping[value];
    }
    // _convertUsbData(appConfig: IAccessor): UsbConfig {
    //   let aliases: UsbAlias[] = [];
    //   let usbAliasesAcccessor = appConfig.get('USB_Aliases');
    //   for (let aliasNum = 0; ; aliasNum++) {
    //     let aliasName = `Alias${aliasNum}`;
    //     if (!usbAliasesAcccessor.has(aliasName)) {
    //       break;
    //     }
    //     let usbAliasRawData = hexStringToBuffer(usbAliasesAcccessor.value(aliasName));
    //     aliases.push(this._convertUsbAlias(usbAliasRawData));
    //   }
    //   return {
    //     aliases: aliases
    //   };
    // }
    // private _convertUsbAlias(data: Uint8Array): UsbAlias {
    //   return this.usbAliasConverter.decode(data);
    // }
    readProfilesConfig(profiles) {
        const results = [];
        for (let i = 0; i < profiles.length; i++) {
            const xmlProfile = profiles[i];
            const name = xmlProfile.value('Name');
            let profile;
            if (name === ANONYMOUS_USER.username) {
                continue;
            }
            else if (isSpecialUser(name)) {
                const specialConfig = {
                    username: xmlProfile.value('Name', 'string'),
                    lifeTime: xmlProfile.value('LifeTime', 'number', 0),
                    key: this.readUserKey(xmlProfile),
                };
                profile = specialConfig;
            }
            else {
                const userConfig = {
                    username: xmlProfile.value('Name', 'string', ''),
                    id: xmlProfile.value('Id', 'number', 0),
                    lifeTime: xmlProfile.value('LifeTime', 'number', 0),
                    key: this.readUserKey(xmlProfile),
                };
                profile = userConfig;
            }
            const subProfilesConfig = xmlProfile.list('IOTizeUser', []);
            if (subProfilesConfig.length > 0) {
                const subProfiles = this.readUserProfile(subProfilesConfig);
                profile.users = subProfiles;
            }
            results.push(profile);
        }
        return results;
    }
    readUserKey(xmlProfile) {
        const scramPwd = xmlProfile.value('Scram_Pwd', 'string', undefined);
        if (scramPwd) {
            // let userSalt = xmlProfile.value('Scram_User_Salt', 'number');
            // specialConfig.salt = userSalt;
            return `0x${scramPwd}`;
        }
        else {
            const key = xmlProfile.value('Pwd', 'string', undefined);
            if (key) {
                return `0x${key}`;
            }
        }
        return undefined;
    }
    readUserProfile(subProfilesConfig) {
        const users = [];
        for (let i = 0; i < subProfilesConfig.length; i++) {
            const xmlUserConfig = subProfilesConfig[i];
            const user = {
                username: xmlUserConfig.value('Name', 'string', ''),
                id: xmlUserConfig.value('Id', 'number', 0),
                key: this.readUserKey(xmlUserConfig),
            };
            users.push(user);
        }
        return users;
    }
    readBundlesConfig(xmlBundles) {
        const result = [];
        for (let i = 0; i < xmlBundles.length; i++) {
            const xmlBundle = xmlBundles[i];
            let aclsXml = [];
            const aclContainer = xmlBundle.get('IOTizeAccessControl', undefined);
            if (aclContainer) {
                aclsXml = aclContainer.list('IOTizeACL', []);
            }
            const acls = {};
            for (let j = 0; j < aclsXml.length; j++) {
                const aclXml = aclsXml[j];
                const profileName = aclXml.value('ProfileName');
                if (profileName === ADMIN_USER.username) {
                    continue;
                }
                const rights = aclXml.value('Rights');
                acls[profileName] = {
                    read: rights.includes('read'),
                    write: rights.includes('write'),
                };
            }
            const bundleConfig = {
                name: xmlBundle.value('GUI_Name'),
                id: parseInt(xmlBundle.value('Id')),
                variables: this.readVariablesConfig(xmlBundle.list('IOTizeVariable', [])),
                acls,
                dataLog: {
                    period: xmlBundle.value('DataLogPeriod', 'number', 0),
                },
                features: this.readSpecialFeatures(xmlBundle.list('Feature', [])),
            };
            result.push(bundleConfig);
        }
        return result;
    }
    readSpecialFeatures(featuresXml) {
        if (featuresXml.length > 0) {
            const result = [];
            for (let i = 0; i < featuresXml.length; i++) {
                const featureId = featuresXml[i].value('FeatureResId', 'number');
                if (featureId in SpecialFeature) {
                    const value = SpecialFeature[featureId]; // TODO check
                    result.push(value);
                }
                else {
                    throw new Error(`Unexpected feature id: ${featureId}`);
                }
            }
            return result;
        }
        else {
            return undefined;
        }
    }
    readVariablesConfig(variables) {
        const result = [];
        for (let i = 0; i < variables.length; i++) {
            const xmlVariable = variables[i];
            const id = xmlVariable.value('Id', 'number');
            const length = xmlVariable.value('Quantity', 'number', 1);
            const dataType = toEnumType(convertToVariableType(xmlVariable), VariableType.Data);
            const name = xmlVariable.value('GUI_Name', 'string', '');
            const unit = xmlVariable.value('GUI_DispUnit', 'string', '') || undefined;
            let meta;
            if (name || unit) {
                meta = {
                    name,
                    unit,
                };
            }
            const isInTapStatic = isTruthy(xmlVariable.value('IsInTap', 'string', '0'));
            const IsInTapVolatil = isTruthy(xmlVariable.value('IsInTapVolatil', 'string', '0'));
            if (IsInTapVolatil || isInTapStatic) {
                const initialValueString = xmlVariable.value('InTap_InitialValueString', 'string', '');
                const initialValue = decodeInitialVariableValue(initialValueString);
                const inTapVariable = {
                    domain: IsInTapVolatil ? 'IN_TAP_VOLATIL' : 'IN_TAP_STATIC',
                    id,
                    length,
                    dataType,
                    meta,
                    value: initialValue,
                };
                result.push(inTapVariable);
            }
            else {
                // if (isModbusTargetConfig){
                //     const modbusVariableConfig: ModbusVariableConfig = {
                //         domain: 'TARGET',
                //         modbusAddress: {
                //         },
                //         id,
                //         length,
                //         dataType,
                //         name,
                //         unit
                //     };
                //     result.push(variableConfig);
                // }
                // else {
                const variableConfig = {
                    domain: 'TARGET',
                    address: toHexNumberConfig(xmlVariable.value('Address', 'number')),
                    id,
                    length,
                    dataType,
                    meta,
                };
                result.push(variableConfig);
                // }
            }
        }
        return result;
    }
    _protocolDataToJsonConfig(protocolData, targetProtocolConfDataLen) {
        if (targetProtocolConfDataLen === 0) {
            return {
                modbus: {
                    offsetFirstRegister: false,
                    slave: 0,
                },
                serial: {
                    baudRate: 115200,
                    bitParity: 'EVEN',
                    dataBits: '_8',
                    handshakeDelimiter: 'NONE',
                    hardwareFlowControl: 'NONE',
                    identification: false,
                    ledStatus: true,
                    physicalPort: 'AUTO',
                    stopBits: 'ONE',
                    timeout: 255,
                },
                usb: {
                    aliases: [],
                },
            };
        }
        if (protocolData.length < 8) {
            throw IoTizeStudioError.invalidKeyValue('TargetProtocolConfData', // TODO change key
            'Protocol configuration data should be at least 8 bytes');
        }
        const ctr1 = protocolData.slice(0, 4);
        const ctr2 = protocolData.slice(4, 8);
        const remaining = protocolData.slice(8);
        //  KaitaiStreamWriter.mergeArrays(ctr2, ctr1).reverse(),
        protocolData = KaitaiStreamWriter.mergeArrays(ctr1.reverse(), ctr2.reverse(), remaining);
        const PROTOCOL_CONF_CTR_LENGHT = 8;
        const reorderedProtocolData = KaitaiStreamWriter.mergeArrays(protocolData.slice(0, PROTOCOL_CONF_CTR_LENGHT).reverse(), protocolData.slice(PROTOCOL_CONF_CTR_LENGHT));
        const protocolConf = tapnpassConverters.tapnpassProtocolConfiguration.decode(reorderedProtocolData);
        const serial = protocolConf.serial;
        const usb = protocolConf.usb;
        return {
            modbus: protocolConf.modbus,
            serial: {
                baudRate: serial.baudRate,
                bitParity: this.toEnumKey(serial.bitParity, SerialSettings.BitParity),
                dataBits: this.toEnumKey(serial.dataBits, SerialSettings.DataBits),
                handshakeDelimiter: this.toEnumKey(serial.handshakeDelimiter, SerialSettings.HandshakeDelimiter),
                hardwareFlowControl: this.toEnumKey(serial.hardwareFlowControl, SerialSettings.HardwareFlowControl),
                physicalPort: this.toEnumKey(serial.physicalPort, SerialSettings.PhysicalPort),
                stopBits: this.toEnumKey(serial.stopBits, SerialSettings.StopBits),
                timeout: serial.timeout,
                identification: false,
                ledStatus: false,
            },
            usb,
        };
    }
}
function toHexNumberConfig(v) {
    return '0x' + v.toString(16);
}
//# sourceMappingURL=data:application/json;base64, 