"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const xml_1 = require("@iotize/common/xml");
const dot_object_1 = require("dot-object");
const debug_1 = require("../../debug");
const errors_1 = require("../../errors");
const TAG = 'XmlEditor';
function setPreferenceValue(editor, name, value) {
    let preferences = editor.get("widget.preference");
    if (preferences === undefined) {
        preferences = [];
    }
    if (!Array.isArray(preferences)) {
        preferences = [
            preferences
        ];
    }
    if (Array.isArray(preferences)) {
        const prefIndex = preferences.findIndex(v => v["#"].name === name);
        if (prefIndex >= 0) {
            preferences[prefIndex]["#"].value = value;
        }
        else {
            preferences.push({
                '#': {
                    name,
                    value
                }
            });
        }
        editor.set("widget.preference", preferences);
    }
}
exports.setPreferenceValue = setPreferenceValue;
class XmlEditor {
    constructor(content) {
        this.content = content;
    }
    static fromTreeFile(tree, path) {
        const fileContent = tree.read(path);
        if (!fileContent) {
            throw errors_1.GeneratorError.unexpectedFileContent(path, `it does not exist`);
        }
        const parsedContent = xml_1.xmlToJson(fileContent.toString(), XmlEditor.parsingOptions);
        if (typeof parsedContent === 'string') {
            throw errors_1.GeneratorError.unexpectedFileContent(path, `it should be a valid XML file with cordova application config`);
        }
        return XmlEditor.fromString(fileContent.toString());
    }
    static fromString(arg0) {
        const parsedContent = xml_1.xmlToJson(arg0, XmlEditor.parsingOptions);
        return new XmlEditor(parsedContent);
    }
    get(xpath) {
        return dot_object_1.pick(xpath, this.content, false);
    }
    set(xpath, newValue) {
        debug_1.debug(TAG, `${xpath}=${JSON.stringify(newValue)}`);
        dot_object_1.set(xpath, newValue, this.content);
    }
    toXml() {
        return xml_1.toXml(this.content, XmlEditor.parsingOptions);
    }
}
exports.XmlEditor = XmlEditor;
XmlEditor.parsingOptions = {
    attrNodeName: "#",
    ignoreAttributes: false,
    attributeNamePrefix: '',
    format: true
};
//# sourceMappingURL=index.js.map