'use strict';

// GLOBAL
const execa = require('execa');
const path = require('path');

// LOCAL
const tools = require('./tools');
const templateUtils = require('../csdr/templates/template-utils');

// FETCH ARGS
const { nexusUser, nexusPassword } = tools.getArgs();


const execute = (folder, command = 'clean test package') => {

  const cwd = folder;
  const execaOptions = { cwd, stdio: 'inherit' };

  tools.logTitle(`Executing maven command : ${command}...`);

  return Promise.resolve()
    .then(() => {
      return templateUtils.generateMavenSettings(nexusUser, nexusPassword);
    })
    .then((mavenSettingsFile) => {
      tools.logInfo('Executing maven build...');
      return execa.shellSync(`mvn ${command} -s ${mavenSettingsFile}`, execaOptions);
    })
    .catch((e) => {
      throw e;
    });
}


const getPomInfos = (folder) => {
  tools.logInfo('Getting pom.xml content...');

  return Promise.resolve()
    .then(() => {

      const xmlContent = tools.getXMLJsContent(path.join(folder, 'pom.xml'));

      tools.logInfo('pom.xml content : ');
      console.log(xmlContent);

      let pomGroupId;
      let pomArtifactId;
      let pomVersion;
      let modulesList = '';

      pomGroupId = xmlContent.project.groupId.toString();
      pomArtifactId = xmlContent.project.artifactId.toString();
      pomVersion = xmlContent.project.version.toString();

      if(xmlContent.project.modules){
        tools.logInfo('Extracting modules list from : ');
        console.log(JSON.stringify(xmlContent.project.modules));
        modulesList = xmlContent.project.modules[0].module.join(",");
      }

      tools.logInfo("GroupId : " + pomGroupId);
      tools.logInfo("ArtifactId: " + pomArtifactId);
      tools.logInfo("Version: " + pomVersion);
      tools.logInfo("Module List: " + modulesList);

      return {
        groupId: pomGroupId,
        artifactId: pomArtifactId,
        version: pomVersion,
        modulesList: modulesList,
      }

    })
    .catch((e) => {
      throw e;
    })
}

module.exports = {
  execute,
  getPomInfos,
}
