'use strict';

const tools = require('../../utils/tools');
const initUtils = require('./init-utils');
const installUtils = require('../install/install-utils');
const configUtils = require('../config/config-utils');

const { skipClone, skipInstall, build } = tools.getArgs();

module.exports.init = (finalResponse) => {
  return (
    Promise.resolve()
      // Initializing .euirc.json local file - the core of CSDR operations
      .then(() => {
        // Initialize config
        return configUtils.init.run(finalResponse);
      })

      // Initializing .meta based on .euirc.json for local respoisitories cloning
      .then(() => {
        return initUtils.meta.init();
      })

      // Cloning repositories based on the .meta file generated
      .then(() => {
        if (!skipClone) {
          return initUtils.repos.init(finalResponse);
        }
      })

      // check and create tsconfig root files
      .then(() => {
        return configUtils.angular.checkConfigFiles(true);
      })

      // adapt and inject particular root data/config for eUI version detected on project
      // if multiple versions of eUI are detected on the same project, an exception is thrown
      .then(() => {
        return initUtils.global.initRootFilesAndResolutions();
      })

      // Install deps based on current config generated => take last know snapshots
      .then(() => {
        // this is only executed for local dev installation,
        // in case of release the initialisation is managed by the application / package themselves
        if (!build && !skipInstall) {
          return installUtils.localDev.install();
        }
      })

      // Attaching app scripts to root package.json
      .then(() => {
        return initUtils.projects.importScripts();
      })

      // Attaching extra tsconfig from project
      .then(() => {
        return initUtils.projects.importExtraTsConfig();
      })

      .then(() => {
        tools.logSuccess('OK => Projects group successfully initialized');
      })

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