import * as plugins from './mod.plugins.js';
import * as paths from '../paths.js';

import { logger } from '../gitzone.logging.js';

export const getTemplatePath = (templateNameArg: string) => {
  return plugins.path.join(paths.templatesDir, templateNameArg);
};

/**
 * receives a template name and returns wether there is a corresponding template
 */
export const isTemplate = async (templateNameArg: string) => {
  return plugins.smartfile.fs.isDirectory(getTemplatePath(templateNameArg));
};

export const getTemplate = async (templateNameArg: string) => {
  if (isTemplate(templateNameArg)) {
    const localScafTemplate = new plugins.smartscaf.ScafTemplate(getTemplatePath(templateNameArg));
    await localScafTemplate.readTemplateFromDir();
    return localScafTemplate;
  } else {
    return null;
  }
};

export const run = async (argvArg: any) => {
  let chosenTemplate: string = argvArg._[1];

  if (!chosenTemplate) {
    const smartinteract = new plugins.smartinteract.SmartInteract();
    const answerBucket = await smartinteract.askQuestion({
      type: 'list',
      default: 'npm',
      message: 'What template do you want to scaffold? (Only showing mpost common options)',
      name: 'templateName',
      choices: ['npm', 'service', 'wcc', 'website'],
    });
    chosenTemplate = answerBucket.value;
  }

  if (await isTemplate(chosenTemplate)) {
    logger.log('info', `found requested template ${chosenTemplate}`);
  } else {
    logger.log('error', `Template ${chosenTemplate} not available`);
    return;
  }

  const localScafTemplate = await getTemplate(chosenTemplate);
  await localScafTemplate.askCliForMissingVariables();
  await localScafTemplate.writeToDisk(paths.cwd);
};