'use strict';

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

// LOCAL
const tools = require('../tools');
const gitUtils = require('../git-utils');
const mavenUtils = require('../maven-utils');
const notificationUtils = require('../notification/notification-utils');

// CSDR RELATED
const templateUtils = require('../../csdr/templates/template-utils');
const configUtils = require('../../csdr/config/config-utils');

// FETCH ARGS
const { branch, dryRun, sonarQubeToken } = tools.getArgs();



const runCore = (pkg, isMaster) => {

  // check at metadata global flag level if enabled
  if (!pkg.standalone) {
    if (!configUtils.global.isSonarEnabled()) {
      tools.logInfo('Sonar scanner globally disabled');
      return Promise.resolve();
    }
  }

  // check at package config level if enabled
  if (dryRun || (pkg.build && pkg.build.sonarScanner === false) ) {
    tools.logInfo('Skipping sonar scanner execution');
    return Promise.resolve();
  }

  return Promise.resolve()
    .then(() => {
      if (pkg.backend) {
        return runBackend(pkg, isMaster);
      } else {
        return runUI(pkg, isMaster);
      }
    })
    .then(() => {
      return notificationUtils.package.sendPackageMessage({
        package: pkg,
        title: '[SONAR SCANNER SUCCESS]',
        subtitle: 'Sonar scanner executed for package, available on https://webgate.ec.europa.eu/devcc-sonarqube'
      });
    })
    .catch((e) => {
      tools.logError(`Error executing sonar scanner for package "${pkg.name}".`);
      console.log(e);

      return notificationUtils.package.sendPackageMessage({
        package: pkg,
        exception: e,
        title: '[SONAR SCANNER FAILED]',
        subtitle: 'Error while executing Sonar scanner'
      });
    });
}



const run = (pkg, isMaster) => {
  tools.logTitle('Executing Sonar scanner');

  if (!pkg.parent) {
    return runCore(pkg, isMaster);

  } else {

    return Promise.resolve()
      .then(() => {
        var linkedPackages = Object.keys(pkg.packages).map(p => {
          const pkg = configUtils.packages.getPackage(p);
          return pkg;
        }).filter(p => {
          return ((p.build && p.build.exec !== false && p.tsPackage !== false))
        });

        return tools.removeArrayDuplicates(linkedPackages, 'name');
      })

      .then((linkedPackages) => Promise.resolve().then(() => {
        return linkedPackages.reduce((promise, pkg) => {
          return promise.then(() => (
            runCore(pkg, isMaster)
          ));
        }, Promise.resolve());
      }))

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




const runUI = (pkg, isMaster) => {
  tools.logTitle('Executing Sonar analysis on UI package...');

  return Promise.resolve()
    .then(() => {
      return gitUtils.getShortHash(pkg.paths.root);
    })
    .then((gitShortHash) => {
      const hasSubEntries = !pkg.srcRootDefault;
      return templateUtils.generateSonarPropertiesUI(
        pkg.name, gitShortHash, pkg.paths.root, hasSubEntries
      );
    })
    .then(() => {
      if (!dryRun) {
        tools.logInfo('Calling Sonar scanner...');

        let SONAR_HOST;
        if (pkg.standalone) {
          SONAR_HOST = configUtils.global.getConfigOptionsStandalone().SONAR_HOST;
        } else {
          SONAR_HOST = configUtils.global.getConfigOptions().SONAR_HOST;
        }

        return execa.shellSync(`sonar-scanner -Dsonar.branch.name=${branch} -Dsonar.host.url=${SONAR_HOST} -Dsonar.login=${sonarQubeToken}`, { cwd: pkg.paths.root, stdio: 'inherit' });
      }
    })
    .catch((e) => {
      throw e;
    });
}





const runBackend = (pkg, isMaster) => {
  tools.logTitle('Executing Sonar analysis on backend package...');

  return Promise.resolve()
    .then(() => {
      tools.logInfo('Generating project template file...');
    })
    .then(() => {
      return mavenUtils.getPomInfos(pkg.paths.root);
    })
    .then((pomInfos) => {
      return templateUtils.generateSonarPropertiesBackend(
        pomInfos.groupId, pkg.name, pomInfos.version, pomInfos.modulesList, pkg.paths.root
      );
    })
    .then(() => {
      tools.logSuccess();
    })

    .then(() => {
      if (!dryRun) {
        tools.logInfo('Calling Sonar scanner...');
        const SONAR_HOST = configUtils.global.getConfigOptions().SONAR_HOST;
        return execa.shellSync(`sonar-scanner -Dsonar.branch.name=${branch} -Dsonar.host.url=${SONAR_HOST} -Dsonar.login=${sonarQubeToken}`, { cwd: pkg.paths.root, stdio: 'inherit' });
      }
    })
    .catch((e) => {
      throw e;
    });
}



module.exports = {
  run,
}
