'use strict';

const tools = require('../../utils/tools');
const gitUtils = require('../../utils/git-utils');

const innerMeta = require('./meta');

const { skipEuiToolsClone, shallowClone } = tools.getArgs();


const getRepos = (project, pkg, prjOnly, pkgOnly) => {
  const metaProjects = innerMeta.getMetaProjects();

  const repos = Object.keys(metaProjects).map((folder) => (
    {
      folder,
      uri: metaProjects[folder],
    }
  ));

  if (pkgOnly) {
    return repos.filter((i) => i.folder.indexOf(pkg) > -1);
  } else {
    if (prjOnly) {
      return repos.filter((i) => i.folder.indexOf(project) > -1);
    } else if (skipEuiToolsClone) {
      return repos.filter((i) => i.folder.indexOf('eui-tools') === -1);
    } else {
      return repos;
    }
  }
}





module.exports.init = (args) => {

  tools.logTitle('Initializing local respositories');

  const repos = getRepos(args.project, args.pkg, args.prjOnly, args.pkgOnly);
  console.log(repos);

  return Promise.resolve()
    .then(() => Promise.resolve().then(() => {
      return repos.reduce((promise, repo) => {
        return promise.then(() => (
          cloneAndCheckout(repo, args)
        ));
      }, Promise.resolve());
    }))

    .then(() => {
      tools.logSuccess('OK => Repositories successfully cloned');
    })

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




const cloneAndCheckout = (repo, args) => {
  if (repo.folder.indexOf('apps/') > -1 && args.skipAppContainers) {
    return Promise.resolve();
  }

  return Promise.resolve()
    .then(() => {
      const branch = innerMeta.getBranchFromRepo(repo);
      let cloneBranch;

      if (branch) {
        cloneBranch = branch;
      } else {
        cloneBranch = args.branch;
      }
      return gitUtils.cloneAndCheckout(repo.uri, repo.folder, cloneBranch, false, shallowClone);
    })

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



