"use strict";

/* eslint-disable operator-linebreak */

/* eslint-disable implicit-arrow-linebreak */
const fs = require('fs');

const {
  log
} = require('..');

const {
  question,
  rl
} = require('./question');

const eslintConfigFiles = ['.eslintrc.js', '.eslintrc.cjs', '.eslintrc.yaml', '.eslintrc.yml', '.eslintrc.json', '.eslintrc'];
const prettierConfigFiles = ['.prettierrc.js', '.prettierrc.json', '.prettierrc', '.prettierrc.yml', '.prettierrc.yaml', '.prettierrc.json5', '.prettierrc.toml', '.prettierrc.cjs', '.prettier.config.js', '.prettier.config.cjs'];

function isConfigExists(fileNames) {
  return fileNames.find(file => {
    if (fs.existsSync(file)) return true;
    return false;
  });
}

async function checkConflicts(files) {
  const conflictFile = isConfigExists(files);

  if (conflictFile) {
    log(`[LINT SETUP] There's already a config exists as named ${conflictFile}`);
    const res = await question('[LINT SETUP] Do you want to overwrite? (y/n): '); // TODO: Next cycle: Need to delete the current config file.
    // if (res === 'y') {
    //   exec(`rm ${conflictFile}`, (err) => {
    //     if (err) log(err);
    //     else {
    //       log('Deleted ', conflictFile);
    //     }
    //   });
    // }

    return res;
  }

  return false;
}

async function promptForPreCommitHook() {
  const res = await question('[LINT SETUP] Do you need a pre-commit hook for formatting and check lint errors in cached files (newly changed)? (y/n): ');
  return res;
}

const getChoices = async () => {
  const eslint = await checkConflicts(eslintConfigFiles);
  const prettier = await checkConflicts(prettierConfigFiles);
  const isESLintAllowed = eslint === false || eslint === 'y';
  const isPrettierAllowed = prettier === false || prettier === 'y';
  const isHookInstallEnabled = (await promptForPreCommitHook()) === 'y';
  rl.close();
  return [isESLintAllowed, isPrettierAllowed, isHookInstallEnabled];
};

module.exports = {
  eslintConfigFiles,
  prettierConfigFiles,
  getChoices
};