const tools = require('@eui/tools/scripts/utils/tools');
const path = require('path');
const utils = require('./utils');
const config = require('./config');
const childProcess = require('child_process');
const execa = require('execa');
const execSync = childProcess.execSync;

module.exports.start = (options) => {
  return Promise.resolve()
    .then(() => {
      return build(options.config, options.targetPath)
    })

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

const build = (cliConfig, targetPath) => {
  let {appName, appType, appSubType, tag, groupId, artifactId, ...args} = cliConfig;

  console.log(`Building app : ${appType}`);

  return Promise.resolve()
    .then(() => {
      let target = targetPath;
      console.log(`--cleaning target : ${target}`);

      if (!tools.isDirEmpty(target)) {
        tools.logError(`Target directory : ${target} is not empty, execute eUI CLI in a blank directory... quitting`);
        throw new Error('DIR_NOT_EMPTY');
      } else {
        return tools.rimraf(`${target}/**/*`);
      }
    })

    .then(() => {

      // BUILD ANGULAR
      if (appType === 'angular' || appType === 'mobile') {
        return Promise.resolve()
          .then(() => {
            console.log('---building angular');
            const angularPath = utils.getAngularPath(targetPath, appName, appType, artifactId);
            console.log(angularPath);
            return copyAngular(angularPath, cliConfig, true);
          })
          .catch((e) => {
            throw e;
          })
      }

      // BUILD web-maven
      if (appType === 'web-maven') {
        return Promise.resolve()
          .then(() => {
            console.log('--building web-maven');
            return tools.copydir(config.webMavenPath, targetPath);
          })
          .then(() => {
            const angularPath = utils.getAngularPath(targetPath, appName, appType);
            return copyAngular(angularPath, cliConfig);
          })
          .catch((e) => {
            throw e;
          })
      }

      // BUILD web-spring-boot
      if (appType === 'web-spring-boot') {
        return Promise.resolve()
          .then(() => {
            console.log('--building web-spring-boot');
            return execSync(`mvn generate-sources -f ./maven-build/pom.xml -Pbuild-web-spring-boot -Dsrc.path=${config.webSpringBootPath} -Dtarget.path=${targetPath} -Dapp.group.id=${groupId} -Dapp.artifact.id=${artifactId}`, {
              cwd: path.join(__dirname),
              stdio: "inherit"
            });
          })
          .then(() => {
            const angularPath = utils.getAngularPath(targetPath, appName, appType, artifactId);
            return copyAngular(angularPath, cliConfig, false);
          })
          .catch((e) => {
            throw e;
          })
      }


      // BUILD symfony
      if (appType === 'web-symfony') {

        return Promise.resolve()
          .then(() => {
            console.log('--cloning eui php starter repository')
            execa.shellSync(`git clone https://${config.webPhpStarterRepo} ${targetPath}`);
          })
          .then(() => {
            console.log('--building web-symfony');
            const angularPath = utils.getAngularPath(targetPath, appName, appType, artifactId);
            return copyAngular(angularPath, cliConfig, false);
          })
          .then(() => {
            execa.shellSync(`npm run init`, { cwd:  path.join(targetPath, 'server'), stdio: "inherit" });
          })
          .catch((e) => {
            throw e;
          })
          .finally(() => {
            return tools.rimraf(`${targetPath}/.git`);
          })
      }

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




const copyAngular = (targetPath, cliConfig, overwrite = true) => {
  return Promise.resolve()
    .then(() => {
      const {angularBasePath} = config;
      const sourcePath = angularBasePath;

      return tools.copydir(sourcePath, targetPath, overwrite);
    })
    .then(() => {
      if (cliConfig.appType === 'mobile') {
        return tools.copydir(config.angularBaseMobilePath, targetPath, overwrite);
      }
    })
    .then(() => {
      if (cliConfig.appOptions && cliConfig.appOptions.length !== 0) {
        cliConfig.appOptions.forEach((item) => {
          if (item !== 'ecl') {
            console.log('Applying option : ' + item);
            tools.copydir(config.optionsPath[item], targetPath, true);
          }
        })
        if (cliConfig.appOptions.includes('ecl') && cliConfig.appOptionsEclTheme) {
          console.log(`eUI ECL theme selected : ` + cliConfig.appOptionsEclTheme);
          tools.copydir(config.optionsPath[cliConfig.appOptionsEclTheme], targetPath, true);
        }
      }
      return Promise.resolve();
    })
    .catch((e) => {
      throw e;
    })
}
