'use strict';


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

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

// INNER MODULES
const innerPackages = require('./packages');
const innerProjects = require('./projects');


// -------------------------------------------------------------------------------------
// Updates the .csdr/.euirc.json, storing locally installed projects and packages names
// --
// Called by "sync" - csdr/sync/sync-utils
// -------------------------------------------------------------------------------------

module.exports.run = () => {
  tools.logInfo('Synching packages and local config');

  // just for recall of the config getter which potentially execute the migrate from old config version
  // const packages = innerPackages.getPackages();

  const pkgFolders = tools.getFolders(path.join(process.cwd(), 'packages'));
  const prjFolders = tools.getFolders(path.join(process.cwd(), 'apps'));
  const hostFolders = tools.getFolders(path.join(process.cwd(), 'hosts'));
  const remoteFolders = tools.getFolders(path.join(process.cwd(), 'remotes'));

  const csdrProjects = innerProjects.getCsdrProjects();

  tools.logInfo('Package folders found:');
  console.log(pkgFolders);

  tools.logInfo('Project folders found:');
  console.log(prjFolders);

  tools.logInfo('Host projects folders found:');
  console.log(hostFolders);

  tools.logInfo('Remotes folders found:');
  console.log(remoteFolders);

  // for projects, we need to take the known rootName based on the folder from the CSDR global config
  let projects = [];
  prjFolders.forEach((prjFolder) => {
    const csdrPrj = csdrProjects.filter((prj) => {
      return prj.name === prjFolder;
    })[0];

    if (csdrPrj) {
      projects.push(csdrPrj.rootName);
    }
  })

  hostFolders.forEach((hostFolder) => {
    const csdrPrj = csdrProjects.filter((prj) => {
      return prj.name === hostFolder;
    })[0];

    if (csdrPrj) {
      projects.push(csdrPrj.rootName);
    }
  })

  tools.logInfo('Project folder remapped to CSDR project config');
  console.log(projects);

  // update the local config file
  const config = {
    projects: projects,
    packages: pkgFolders,
    remotes: remoteFolders
  };
  if (tools.isDirExists(path.join(process.cwd(), '.config'))) {
    tools.writeJsonFileSync(path.join(process.cwd(), '.config', '.euirc.json'), config);
  } else {
    tools.writeJsonFileSync(path.join(process.cwd(), '.csdr', '.euirc.json'), config);
  }
}
