'use strict';

const path = require('path');

const tools = require('../../tools');
const configUtils = require('../../../csdr/config/config-utils');

let { skipLint, fix } = tools.getArgs();

const getProjectInfos = () => {
  // getting the project from installed config
  const prj = configUtils.projects.getProject();

  // exit if project can't be found in the local installed config
  if (!prj) {
    tools.logError('ERROR!!! Unable to find project to be used');
    tools.logInfo('usage : eui-scripts build-app <project-name>');
    throw new Error('PROJECT_NOT_FOUND');
  }

  return prj;
};


module.exports.run = () => {

  const currentProject = getProjectInfos();

  // getting param from project config
  if (currentProject.build) {
    if (currentProject.build.skipLint) {
      skipLint = true;
    }
  }

  return Promise.resolve()
    .then(() => {
      if (!skipLint) {
        tools.logInfo(`TS Linting application...`);
        let tsLintPath = currentProject.paths.tslintPath;
        let esLintPath = currentProject.paths.eslintPath;

        // TODO: remove TSLint since it's deprecated and should not be used by projects in the future
        if(tsLintPath) {
          tsLintPath = path.join(tsLintPath);
          let tsConfigPath = path.join(currentProject.paths.angularPath, 'tsconfig.app.json');
          tools.logWarning('TSLint is deprecated and will be removed in the future. Consider migrating to ESLint')
          if (!tools.isFileExists(tsConfigPath)) {
            tsConfigPath = path.join(currentProject.paths.angularPath, 'src', 'tsconfig.app.json');
          }
          if (tools.isFileExists(tsConfigPath)) {
            tools.logInfo(`running tslint -c ${tsLintPath} -p ${tsConfigPath}`);
            return tools.runScript(`tslint -c ${tsLintPath} -p ${tsConfigPath}`);
          }
        } else if (esLintPath) {
          // the project path information are located inside the .eslintrc.json
          let script = `ng lint ${currentProject.name}`;
          if (fix) {
            script += ' --fix';
          }
          tools.logInfo(`running ${script}`);
          return tools.runScript(script);
        } else {
          tools.logError(`No ESLint or TSLint configuration found for the project...skipping`);
        }

      }
    })

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