import ElasticsearchPublisher from './elasticsearch-publisher.js'
import VaultService from '../../services/vault-service.js'
import tools from '@eui/tools/scripts/utils/tools.js'
const { vaultUser, vaultPassword } = tools.getArgs();

import { Command } from 'commander'
const program = new Command();
import fs from 'fs';
import path from 'path';
import superagent from 'super-agent';
import { ProxyAgent } from 'proxy-agent';

program.requiredOption('-c, --config <config>', 'config json');

(async function() {
  program.parse(process.argv);
  let options = program.opts();
  options.config = JSON.parse(options.config);

  if (!options.config.vaultConfig){
    throw new Error("esConfig should contain vaultConfig");
  }
  if (!options.config.vaultConfig.endpoint){
    throw new Error("esConfig.vaultConfig should contain vault endpoint");
  }
  let vconf = {
    vaultConfig:{
      endpoint: options.config.vaultConfig.endpoint,
      user: vaultUser,
      password: vaultPassword
    }
  }
  let vault = new VaultService(vconf);
  await vault.getSecret(options.config.vaultConfig.path, options.config.vaultConfig.key).then(value => {
    if (value[options.config.vaultConfig.key]){
      Object.keys(value[options.config.vaultConfig.key]).forEach(varKey => {
        if (!options.config[varKey]){
          options.config[varKey] = value[options.config.vaultConfig.key][varKey]
        }
      })
    }
  })

  let request = superagent;
  let proxy = false;
  let proxyA = false;
  if (process.env.http_proxy){
      proxy = process.env.http_proxy;
      proxyA = new ProxyAgent();
  }

  let response = "";
  if (proxy) {
    response = await request
    .get(options.config.jsonLink)
    .agent(proxyA);
  } else {
    response = await request
    .get(options.config.jsonLink);
  }

  let log = response.body;

  let tmpFolder = path.join('.', '.tmp');
  if (!fs.existsSync(tmpFolder)){
    fs.mkdirSync(tmpFolder);
  }

  let filename = path.parse(log.jsonLink).base;
  let filepath = path.join(tmpFolder, filename);

  fs.writeFileSync(filepath,
    JSON.stringify(log,null,2), function(err) {
          if (err) {
              return console.error("Error writing writing logfile in es publisher script: " + err);
          }
      }
  );

  console.log("Publishing");

  let pub = new ElasticsearchPublisher(options.config);
  if (options.config.publish &&
    ( options.config.publish === 'always' ||
    ( options.config.publish === 'fail' && log.allResults.failed_describes > 0 ))) {
    await pub.publish(filepath);
  }
})();
