import chalk from 'chalk';
import { ask } from 'stdio';
import { createTempProjectInstance, compilePackage, compileTemplateFile } from './lib';
import { mkdir, rmdir, stat } from 'fs/promises';
import { COMPONENTS_DIR, PROJECT_DIR } from './meta';
import { logStatus } from './log';
import { existsSync } from "fs";
import { join } from "path";
let componentNameArgument = '';
let nonInteractive = false;
const checkComponentWasBuilt = async (componentName) => {
  let isBuildInCustom = false;
  let isBuildInShared = false;
  let isBuildInSrc = false;
  // isBuildInCustom = await stat(`${COMPONENTS_DIR}/customs/${componentName}/readme.md`).then(statInfo => statInfo.isDirectory())
  isBuildInCustom = await existsSync(`${COMPONENTS_DIR}/customs/${componentName}/readme.md`).valueOf();
  // isBuildInShared = await stat(`${COMPONENTS_DIR}/shared/${componentName}/readme.md`) .then(statInfo => statInfo.isDirectory())
  isBuildInShared = await existsSync(`${COMPONENTS_DIR}/shared/${componentName}/readme.md`).valueOf();
  isBuildInSrc = await existsSync(`${COMPONENTS_DIR}${componentName}/readme.md`).valueOf();
  return !!(isBuildInCustom || isBuildInShared || isBuildInSrc);
};
const checkComponentExistance = async (componentName) => {
  let componentExistenceInCustom = false;
  let componentExistenceInShared = false;
  let componentExistence = false;
  componentExistenceInCustom = await existsSync(`${COMPONENTS_DIR}/customs/${componentName}`).valueOf();
  componentExistenceInShared = await existsSync(`${COMPONENTS_DIR}/shared/${componentName}`).valueOf();
  componentExistence = await existsSync(`${COMPONENTS_DIR}/${componentName}`);
  // return await stat(`${COMPONENTS_DIR}/customs/${componentName}`)  .then(statInfo => statInfo.isDirectory())
  //   .catch(_error => {
  //     // will be noticed at line 40
  //   })||await stat(`${COMPONENTS_DIR}/shared/${componentName}`)
  //   .then(statInfo => statInfo.isDirectory())
  //   .catch(_error => {
  //     // will be noticed at line 40
  //   })
  return !!(componentExistenceInCustom || componentExistenceInShared || componentExistence);
};
const askComponentName = async (exist, componentName) => {
  if (!exist) {
    console.log(`Component ${componentName} ${chalk.red('not found')}, create it with ${chalk.blue('nx run stencil:generate')} first or enter another component name.`);
    if (!nonInteractive) {
      await askComponentName(exist, componentName);
    }
    else {
      return;
    }
  }
  else {
    const built = await checkComponentWasBuilt(componentName);
    if (!built) {
      console.log(`Component ${componentName} ${chalk.redBright('build error')}`);
      return;
    }
    logStatus({
      actionDoing: 'Isolating',
      subject: componentName,
    });
    // componentName = await existsSync(`${COMPONENTS_DIR}/customs/${componentName}/readme.md`).valueOf() ?'/customs/'+componentName:await existsSync(`${COMPONENTS_DIR}/shared/${componentName}/readme.md`).valueOf()?'/shared/'+componentName:componentName;
    //TODO: refactor devo passare un parametro opzionale per queste tre funzioni che mi identifichi customs o shared
    const subdir = await existsSync(`${COMPONENTS_DIR}/customs/${componentName}/readme.md`).valueOf() ? '/customs/' : await existsSync(`${COMPONENTS_DIR}/shared/${componentName}/readme.md`).valueOf() ? 'shared' : '';
    await compilePackage(componentName, subdir);
    await compileTemplateFile(componentName, '.gitlab-ci.yml', subdir);
    await createTempProjectInstance(componentName, subdir);
  }
};
if (process.argv.length === 3) {
  componentNameArgument = process.argv[2];
  nonInteractive = true;
  console.log(`${chalk.yellow('Non-interactive mode')} using ${componentNameArgument} component name`);
}
const main = async () => {
  console.log(`This script will ${chalk.green('isolate')} a stencil component and will create package.json if missing into a an isolated stencil project, ready to be published`);
  if (!nonInteractive) {
    const continueTask = await ask('Continue?', { options: ['Y', 'n', ''] });
    if (continueTask === 'n') {
      return;
    }
  }
  console.log('Make .build dir with script "ISOLATE COMPONENT"');
  let componentName = '';
  if (!nonInteractive) {
    const inputName = await ask('Component name sw-');
    componentName = `sw-${inputName}`;
  }
  else {
    componentName = componentNameArgument;
  }
  let exist = await checkComponentExistance(componentName);
  exist = exist;
  const buildDirExist = await stat(`${PROJECT_DIR}/.build`)
    .then(statInfo => statInfo.isDirectory())
    .catch(_error => {
    // will be noticed at line 40
  });
  if (exist) {
    if (!buildDirExist) {
      await mkdir(PROJECT_DIR + '/.build').then(() => console.log('.build created'));
    }
    else {
      if (!nonInteractive) {
        const continueTask = await ask('Remove and recreate the entire .build [1] or only the component in .build[2]?, default[1]', { options: ['1', '2', ''] });
        if (continueTask === '2') {
          const existComponentInBuild = existsSync((join(PROJECT_DIR + '/.build', componentName)));
          if (existComponentInBuild) {
            await rmdir(PROJECT_DIR + '/.build/' + componentName, { recursive: true });
          }
        }
        else {
          await rmdir(PROJECT_DIR + '/.build', { recursive: true });
          await mkdir(PROJECT_DIR + '/.build').then(() => console.log('.build re-created'));
        }
      }
      else {
        await rmdir(PROJECT_DIR + '/.build', { recursive: true });
        await mkdir(PROJECT_DIR + '/.build').then(() => console.log('.build re-created'));
      }
    }
  }
  await askComponentName(exist, componentName);
};
main();
