const ui = require('./ui');
const { isLicenseFormatValid } = require('./license');
const {
  LANGUAGE_CHOICES,
  createTranslator,
  detectDefaultLanguage,
  normalizeLanguage
} = require('./i18n');

function makeCancel(t) {
  return () => {
    throw new Error(t('prompt.cancelled'));
  };
}

async function promptLanguage(language) {
  const preferredLanguage = normalizeLanguage(language);
  if (preferredLanguage) {
    return preferredLanguage;
  }

  const detectedLanguage = detectDefaultLanguage();
  const t = createTranslator(detectedLanguage);

  const value = await ui.select({
    message: t('prompt.language.select'),
    initialValue: detectedLanguage,
    options: LANGUAGE_CHOICES.map((choice) => ({
      value: choice.value,
      label: choice.title,
    })),
    onCancel: makeCancel(t),
  });

  return normalizeLanguage(value) || detectedLanguage;
}

async function promptLicenseKey(initial = '', options = {}) {
  const t = options.t || createTranslator(options.language);
  const value = await ui.text({
    message: t('prompt.license.enter'),
    initialValue: initial,
    validate: (v) => (isLicenseFormatValid(v) ? undefined : t('prompt.license.invalid')),
    onCancel: makeCancel(t),
  });
  return value;
}

async function promptProjectName(options = {}) {
  const t = options.t || createTranslator(options.language);
  const value = await ui.text({
    message: t('prompt.projectName.enter'),
    initialValue: t('prompt.projectName.default'),
    validate: (v) => (v && v.trim() ? undefined : t('prompt.projectName.required')),
    onCancel: makeCancel(t),
  });
  return String(value).trim();
}

module.exports = {
  createTranslator,
  promptLicenseKey,
  promptLanguage,
  promptProjectName,
};
