"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const data_accessor_1 = require("@iotize/common/data-accessor");
const iotize_studio_1 = require("@iotize/device-client.js/config/iotize-studio");
const config_generator_1 = require("../config-generator");
const tap_config_parser_1 = require("../tap-config-parser");
const utility_1 = require("../utility");
const ChoicesAdapter_1 = __importDefault(require("./adapters/ChoicesAdapter"));
const TextAdapter_1 = __importDefault(require("./adapters/TextAdapter"));
const protocol_adapter_1 = __importDefault(require("./extra-adapters/protocol-adapter"));
function convertToArrayIfNot(d) {
    return !Array.isArray(d) ? [d] : d;
}
exports.convertToArrayIfNot = convertToArrayIfNot;
function convertIoTizeStudioPageConfig(configGenerator, iotizeStudioConfigModel, pages, key) {
    const type = key.substr(`GUI_`.length);
    const pageAccessor = pages.get(key, undefined);
    if (!pageAccessor) {
        throw new Error(`Missing Iotize Studio configuration key: ${key}`);
    }
    const pageInfo = pageAccessor.data;
    const adapter = {
        iotizeStudioConfig: iotizeStudioConfigModel,
        accessor: pageAccessor,
        extraOptions: {},
        configGenerator
    };
    if (typeof pageInfo['enabled'] === "string") {
        pageInfo['enabled'] = pageInfo['enabled'] === "true";
    }
    let page = Object.assign({}, pageInfo);
    try {
        const adapterPath = `./page-adapters/${type}Adapter`;
        // debug(`ConfigAdapter: render ${adapterPath}`)
        const adpaterFct = require(adapterPath);
        page = adpaterFct.default(adapter, page);
    }
    catch (err) {
        console.warn(`No adapter for ${type}: ${err}`);
    }
    return page;
}
exports.convertIoTizeStudioPageConfig = convertIoTizeStudioPageConfig;
function parseButtonActions(buttonChoicesString) {
    const buttonActions = buttonChoicesString.split(';')
        .map((entryString => {
        const [key, text] = entryString.split('=', 2);
        if (text === undefined || key === undefined || text.length === 0 || key.length === 0) {
            return undefined;
        }
        return {
            name: text,
            value: parseInt(key, 10)
        };
    }))
        .filter(v => v !== undefined);
    return buttonActions;
}
exports.parseButtonActions = parseButtonActions;
function parseSelectOptions(choices) {
    return parseButtonActions(choices)
        .map(v => {
        return {
            key: v.value,
            text: v.name
        };
    });
}
exports.parseSelectOptions = parseSelectOptions;
class IoTizeStudioConfigAdapter {
    static createAppConfigFromIotizeStudioConfig(xmlConfigContent) {
        const tapConfigSchema = tap_config_parser_1.parseTapConfig(xmlConfigContent);
        const iotizeStudioConfigModel = iotize_studio_1.IotizeConfigFactory.fromXML(xmlConfigContent);
        const iotizeStudioDotAccessor = new data_accessor_1.DotAccessor(tap_config_parser_1.iotizeStudioConfigToJson(xmlConfigContent));
        const iotizeConfiguration = iotizeStudioDotAccessor.get('IOTizeConfiguration', undefined);
        if (!iotizeConfiguration) {
            console.warn(' /!\\ Iotize studio configuration file does not have "IOTizeConfiguration" attribute. Create app with default config  /!\\ ');
            return undefined;
        }
        const xappConfig = iotizeConfiguration.get('GUI_XAppConfig', undefined);
        if (!xappConfig) {
            console.warn(' /!\\ Iotize studio configuration file does not have "GUI_XAppConfig" attribute. Create app with default config  /!\\ ');
            return undefined;
        }
        const configGenerator = config_generator_1.ConfigGenerator.fromTapConfig(tapConfigSchema, xmlConfigContent);
        if (xappConfig) {
            const logo = xappConfig.get('GUI_logo', undefined);
            if (logo) {
                const logoOptions = utility_1.convertXMLNodeToType(logo);
                if (logoOptions) {
                    configGenerator.schema.app.logo = logoOptions;
                }
            }
            const app = xappConfig.get('GUI_app', undefined);
            if (app) {
                configGenerator.schema.app.version = app.value('version', 'string', configGenerator.schema.app.version || '0.0.1');
            }
            const splashScreen = xappConfig.get('GUI_splashScreen', undefined);
            if (splashScreen) {
                const splashOptions = utility_1.convertXMLNodeToType(splashScreen);
                if (splashOptions) {
                    configGenerator.schema.app.splashScreen = splashOptions;
                }
            }
            IoTizeStudioConfigAdapter.createAppTheme(xappConfig, configGenerator.appTheme);
            const pages = xappConfig.get('GUI_pages', undefined);
            if (pages) {
                // tslint:disable-next-line: forin
                for (const key in pages.data) {
                    convertIoTizeStudioPageConfig(configGenerator, iotizeStudioConfigModel, pages, key);
                }
            }
            const hostProtocolsNode = xappConfig.get('GUI_hostProtocols', undefined);
            if (hostProtocolsNode) {
                configGenerator.connectionPage(undefined, {
                    protocols: protocol_adapter_1.default({ accessor: hostProtocolsNode })
                });
            }
        }
        const tapDevicePage = configGenerator.tapDevicePage();
        configGenerator.notFoundPage();
        configGenerator.tapLoginPage();
        const profiles = iotizeStudioConfigModel.profiles()
            .filter(profile => {
            // console.info('PROFILE: ', profile.data.$.GUI_ManagedByApp,  profile);
            return profile.data && profile.data.$ && profile.data.$.GUI_ManagedByApp && profile.data.$.GUI_ManagedByApp.toLocaleLowerCase() === "yes";
        });
        // .map(p => p.name());
        const variables = iotizeStudioConfigModel.variables();
        if (profiles.length > 0 && variables.length > 0) {
            const page = configGenerator.monitoringPage(undefined, profiles);
            configGenerator.addDefaultPageMenu(page);
            tapDevicePage.defaultPage = page.path;
        }
        else {
            configGenerator._logger.warn(profiles.length === 0 ? 'No profiles' : 'No variables');
        }
        return configGenerator;
    }
    static createAppTheme(xAppConfig, appThemeBuilder) {
        const appTheme = xAppConfig.get("GUI_appTheme", undefined);
        if (!appTheme) {
            console.warn('Cannot find render GUI_appTheme key');
            return;
        }
        for (const colorName of ['primary', 'secondary', 'tertiary']) {
            const color = appTheme.value(colorName, 'number', undefined);
            if (color !== undefined) {
                appThemeBuilder.setColor(colorName, color);
            }
        }
    }
    static renderOptionsToComponent(input) {
        if (!input.accessor.has('GUI_renderType')) {
            console.warn('Cannot find render GUI_renderType key');
            return undefined;
        }
        const type = input.accessor.value('GUI_renderType', 'string');
        switch (type) {
            case 'Text':
            case 'Password':
            case 'Number':
            case 'Select':
                return TextAdapter_1.default(input);
            case 'Buttons':
            case 'Choices':
                return ChoicesAdapter_1.default(input);
            default:
                try {
                    return require(`./adapters/${type}Adapter`).default(input);
                }
                catch (err) {
                    console.warn('Cannot find render type: ', type, err);
                }
                return undefined;
        }
    }
}
exports.IoTizeStudioConfigAdapter = IoTizeStudioConfigAdapter;
function extractDigitsInfo(variableConfig) {
    const digitsForFloat = variableConfig.attribute("GUI_htmlDigitsFloat");
    if (digitsForFloat) {
        return `1.${digitsForFloat}-${digitsForFloat}`;
    }
    return undefined;
}
exports.extractDigitsInfo = extractDigitsInfo;
//# sourceMappingURL=config-adapter.js.map