
const path = require('path');
const fs = require("fs")
const et = require('elementtree')
const fse = require('fs-extra')

const srcCordovaPath = path.resolve(__dirname,'../src-cordova/')
const configFilePath = path.join(srcCordovaPath,'config.xml')
const packageJson = require(path.resolve(__dirname,'../package.json'))

module.exports = function (ctx,BASE_URL){
  const doc = et.parse(fs.readFileSync(configFilePath, 'utf-8'))
  const root = doc.getroot()

  el = root.find('./preference[@name="AppendUserAgent"]');
  el.attrib['value'] = packageJson.config['AppendUserAgent']+"/"+packageJson.version
  el = root.find('./platform[@name="android"]/allow-navigation');
  el.attrib['href'] = BASE_URL
  // save config.xml
  const content = doc.write({ indent: 4 })
  fs.writeFileSync(configFilePath, content, 'utf8')
  console.log('更新 src-cordova/config.xml')
}

function findOrCreate (root, name) {
  var ret = root.find(name);
  if (!ret) {
      ret = new et.Element(name);
      root.append(ret);
  }
  return ret;
}
