'use strict';

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

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



module.exports.init = () => {

  tools.logTitle('Generating .meta file');

  const metaFile = path.resolve(process.cwd(), '.meta');

  return Promise.resolve()
    .then(() => {

      let content = {
        projects: {}
      };

      // writing local projects
      tools.logInfo('Populating projects');
      const projects = configUtils.projects.getProjects();
      projects.forEach((prj) => {
        if (prj) {
          content.projects[prj.folder] = prj.repository;
        }
      });

      // writing local packages
      tools.logInfo('Populating packages');
      const packages = configUtils.packages.getPackages();
      packages.forEach((pkg) => {
        if (pkg) {
          if (configUtils.global.isCsdr()) {
            content.projects['packages/' + pkg.name] = pkg.repository;
          } else {
            content.projects['packages/' + pkg.name] = pkg.name;
          }
        }
      });

      tools.logInfo('Writing file')
      tools.writeJsonFileSync(metaFile, content);
    })

    .then(() => {
      tools.logSuccess();
    })

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



module.exports.getMetaProjects = () => {
  const meta = tools.getFileContent(path.join(process.cwd(), '.meta'));

  const { projects } = JSON.parse(meta);

  return projects;
}


module.exports.getBranchFromRepo = (repo) => {
  tools.logInfo(`Getting branch from meta repo : ${repo.folder}`);
  const config = configUtils.global.getConfig();

  if (config.packagesBranches && config.packagesBranches.length !== 0) {
    const pkg = configUtils.packages.getPackageByRepository(repo.uri);
    const pkgBranch = config.packagesBranches.find(p => p.name === pkg.name);
    if (pkgBranch) {
      return pkgBranch.branch;
    }

  } else {
    return null;
  }
}
