"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utility_1 = require("./utility");
const ionic_1 = require("./ionic");
const schematics_1 = require("@angular-devkit/schematics");
const dependencies_1 = require("@schematics/angular/utility/dependencies");
function updateCordovaConfig(tree, cb) {
    utility_1.updateXMLFile(tree, 'config.xml', cb);
}
exports.updateCordovaConfig = updateCordovaConfig;
function addCordovaPluginFromIonicCommand(_, name, version) {
    let pluginName = `${name}${(version ? `@${version}` : '')}`;
    // console.info(`cordova plugin add ${pluginName}`);
    return ionic_1.runCordovaCommand([
        'plugin',
        'add',
        pluginName
    ]);
}
exports.addCordovaPluginFromIonicCommand = addCordovaPluginFromIonicCommand;
function addCordovaPlugin(tree, pluginInfo) {
    addCordovaPluginToConfig(tree, {
        name: pluginInfo.id,
        spec: `${pluginInfo.package}@${pluginInfo.spec}`
    });
    dependencies_1.addPackageJsonDependency(tree, {
        name: pluginInfo.package,
        version: pluginInfo.version || pluginInfo.spec,
        type: dependencies_1.NodeDependencyType.Default
    });
}
exports.addCordovaPlugin = addCordovaPlugin;
function addCordovaPluginToPackageJson(tree, pluginInfo) {
    utility_1.updatePackageFile(tree, (data) => {
        if (!data.cordova) {
            data.cordova = {};
        }
        if (!data.cordova.plugins) {
            data.cordova.plugins = {};
        }
        if (!(pluginInfo.name in data.cordova.plugins)) {
            data.cordova.plugins[pluginInfo.name] = {};
        }
        return data;
    });
}
exports.addCordovaPluginToPackageJson = addCordovaPluginToPackageJson;
function addCordovaPluginToConfig(tree, pluginInfo) {
    updateCordovaConfig(tree, (config) => {
        let widget = config.get('widget');
        if (!widget) {
            throw new schematics_1.SchematicsException('This project does not have a valid config.xml file. Missing node "widget".');
        }
        // console.info('NNNNN', widget.plugin);
        if (!widget.plugin) {
            widget.plugin = [];
        }
        if (typeof widget.plugin === "object" && !Array.isArray(widget.plugin)) {
            widget.plugin = [widget.plugin];
        }
        if (!Array.isArray(widget.plugin)) {
            throw new schematics_1.SchematicsException('Cordova plugin list should be an array');
        }
        let hasPlugin = widget.plugin.find((entry) => {
            return entry['#'].name === pluginInfo.name;
        });
        if (!hasPlugin) {
            widget.plugin.push({
                '#': {
                    name: pluginInfo.name,
                    spec: pluginInfo.spec
                }
            });
        }
        else {
            console.info(`Plugin ${pluginInfo.name} is already added`);
        }
    });
}
exports.addCordovaPluginToConfig = addCordovaPluginToConfig;
//# sourceMappingURL=cordova.js.map