'use strict';

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

// LOCAL
const tools = require('../../utils/tools');
const configUtils = require('../config/config-utils');
const gitUtils = require('../../utils/git-utils');
const installUtils = require('../install/install-utils');




const importPackage = (pkg, args) => {
  tools.logTitle(`importing package ${pkg.name}`);

  if (pkg.parent) {
    tools.logInfo('Parent package ... skipping import');

  } else {
    if (pkg.tsPackage !== false) {
      if (!pkg.element) {
        configUtils.angular.registerAngularPackage(pkg, args.reset);
      } else if (pkg.element) {
        configUtils.angular.registerAngularProjectDef(pkg, args.reset, true);
      } else {
        configUtils.angular.registerAngularProjectDef(pkg, args.reset);
      }
      if (pkg.pathInclude !== false && !pkg.element) {
        configUtils.angular.registerModulePaths(pkg, args.reset);
      }
      tools.logSuccess('OK => package imported');

    } else {
      tools.logInfo('Non TS package... skipping registration');
    }
  }
}




module.exports.importPackages = (args = {}) => {

  tools.logTitle('Importing configuration of packages');

  // checking configFiles / force reset on sync
  configUtils.angular.checkConfigFiles(args.reset);

  // registering package in local config

  // in case of "only" param we initialize only the package or remote provided as arg
  if (args.pkgOnly || args.remoteOnly) {
    if (args.pkg) {
      importPackage(configUtils.packages.getPackage(args.pkg), args);
    } else if (args.remote) {
      importPackage(configUtils.remotes.getRemote(args.remote), args);
    }

  // otherwise all known packages are re-registered (in case of sync this happens by default to force refresh packages config)
  } else {
    const packages = configUtils.packages.getPackages();

    packages.forEach((p) => {
      importPackage(p, args);
    })
  }
}


module.exports.cloneHostPackage = (prj) => {
  if (!prj.hostPackage || prj.externalSourcesOnInit === false) {
    return;
  }

  tools.logTitle('Initializing host package');

  let pkg;

  return Promise.resolve()
    .then(() => {
      tools.logInfo(`Fetching host package info : ${prj.hostPackage}`);
      pkg = configUtils.packages.getPackageByNpmPkg(prj.hostPackage, true);
      if (!pkg) {
        throw new Error('Invalid host package provided / unknown to CSDR config');
      }
      if (configUtils.global.isCsdr()) {
        return gitUtils.cloneAndCheckout(pkg.repository, path.join(process.cwd(), 'packages', pkg.name), 'master');
      } else {
        return gitUtils.cloneRepoStandalone(pkg.name, path.join(process.cwd(), 'packages', pkg.name));
      }
    })

    .then(() => {
      const newPackages = [];
      newPackages.push(pkg.name);
      return configUtils.global.updateConfig({ packages: newPackages });
    })

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


module.exports.installHostPackage = (projectName) => {

  // TODO to be removed - only sources are pulled / not installed
  // const project = configUtils.projects.getProject(projectName);

  // if (!project.hostPackage || project.externalSourcesOnInit === false) {
  //   return;
  // }

  // tools.logTitle('Installing host package');

  // return Promise.resolve()
  //   .then(() => {
  //     const pkg = configUtils.packages.getPackageByNpmPkg(project.hostPackage, true);
  //     if (!pkg) {
  //       throw new Error('Invalid host package provided / unknown to CSDR config');
  //     }
  //   })

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


module.exports.importScripts = () => {
  return Promise.resolve()
    .then(() => {
      tools.logTitle("Init scripts for local packages");
      const packages = configUtils.packages.getPackages();

      const rootPackageJsonFile = path.join(process.cwd(), 'package.json')
      const rootPackageJson = require(rootPackageJsonFile);

      packages.forEach((p) => {
        const scriptsFile = path.join(p.paths.root, 'scripts.json');
        if (tools.isFileExists(scriptsFile)) {
          tools.logInfo(`Processing scripts.json file for package:  ${p.name}`);

          const scriptsJson = require(scriptsFile);
          rootPackageJson.scripts = { ...rootPackageJson.scripts, ...scriptsJson };
        }
      });

      tools.logInfo('Updating root package.json');
      tools.writeJsonFileSync(rootPackageJsonFile, rootPackageJson);
    })
    .catch((e) => {
      throw e;
    })
}


module.exports.injectStandaloneResources = (pkg) => {
  const euiVersion = configUtils.packages.getPackageEuiVersion(pkg);
  const skeletonPath = path.join(__dirname, 'standalone', euiVersion);

  tools.copy(skeletonPath, pkg.paths.root);
}
