'use strict';

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

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

const tools = require('../../utils/tools');

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



module.exports.sync = () => {
  return Promise.resolve()
  .then(() => {
    tools.logInfo('Resetting package.json');

    if (tools.isDirExists(path.join(process.cwd(), '.config'))) {
      return tools.copy(path.join(process.cwd(), '.config', 'package.json.reset'), path.join(process.cwd(), 'package.json'));
    } else {
      return tools.copy(path.join(process.cwd(), '.csdr', 'package.json.reset'), path.join(process.cwd(), 'package.json'));
    }
  })
  .then(() => {
    tools.logInfo('Removing yarn.lock');
    return tools.remove(path.join(process.cwd(), 'yarn.lock'));
  })
  .then(() => {
    tools.logSuccess();
  })
  .then(() => {
    if (!skipPull) {
      tools.logInfo(`Pulling root folder ...`);
      return execa.shellSync(`git pull`, { cwd: path.join(process.cwd()), stdio: 'inherit' });
    }
  })
  .then(() => {
    tools.logSuccess();
  })
  .then(() => {
    return configUtils.sync.run();
  })
  .then(() => {
    return initUtils.packages.importPackages({reset: true});
  })
  .then(() => {
    return initUtils.packages.importScripts();
  })
  .then(() => {
    return initUtils.projects.importScripts();
  })
  .then(() => {
    return initUtils.projects.importExtraTsConfig();
  })
  .then(() => {
    return initUtils.projects.importExternalFeatures();
  })
  .then(() => {
    return initUtils.projects.importExternalSources();
  })
  .then(() => {
    return initUtils.projects.importExternalMock();
  })
  .then(() => {
    return initUtils.meta.init();
  })
  .then(() => {
    return initUtils.global.initRootFilesAndResolutions();
  })
  .then(() => {
    if (!skipInstall) {
      return installUtils.localDev.install();
    }
  })
  .catch((e) => {
    throw e;
  })
}
