import chalk from 'chalk';
import { COMPONENTS_DIR } from './meta';
import { stat } from 'fs/promises';
import { logStatus } from './log';
import dirTree from "directory-tree";
import { findPackageToDelete, findGitlabToDelete } from "./lib";
const checkComponentWasBuiltForCustoms = async (componentName) => {
  return await stat(`${COMPONENTS_DIR}/customs/${componentName}/readme.md`)
    .then(statInfo => statInfo.isFile())
    .catch(error => {
    throw Error(chalk.red(error));
  });
};
const checkComponentExistanceForCustoms = async (componentName) => {
  return await stat(`${COMPONENTS_DIR}/customs/${componentName}`)
    .then(statInfo => statInfo.isDirectory())
    .catch(_error => {
    // will be noticed at line 40
  });
};
const checkComponentWasBuiltForShared = async (componentName) => {
  return await stat(`${COMPONENTS_DIR}/shared/${componentName}/readme.md`)
    .then(statInfo => statInfo.isFile())
    .catch(error => {
    throw Error(chalk.red(error));
  });
};
const checkComponentExistanceForShared = async (componentName) => {
  return await stat(`${COMPONENTS_DIR}/shared/${componentName}`)
    .then(statInfo => statInfo.isDirectory())
    .catch(_error => {
    // will be noticed at line 40
  });
};
const cleanAllPJGL = async () => {
  dirTree(COMPONENTS_DIR, {
    extensions: /\.tsx$/,
  }, async (_item) => {
    let componentName = _item.name;
    componentName = componentName.replace('.tsx', '');
    const existCustoms = await checkComponentExistanceForCustoms(componentName);
    const existShared = await checkComponentExistanceForShared(componentName);
    if (!existCustoms) {
      console.log(`Component ${componentName} ${chalk.red('not found')}, create it with ${chalk.blue('nx run stencil:generate')} first or enter another component name.`);
    }
    else {
      const built = await checkComponentWasBuiltForCustoms(componentName);
      if (!built) {
        console.log(`Component ${componentName} ${chalk.redBright('build error')}`);
        return;
      }
    }
    if (!existShared) {
      console.log(`Component ${componentName} ${chalk.red('not found')}, create it with ${chalk.blue('nx run stencil:generate')} first or enter another component name.`);
    }
    else {
      const built = await checkComponentWasBuiltForShared(componentName);
      if (!built) {
        console.log(`Component ${componentName} ${chalk.redBright('build error')}`);
        return;
      }
    }
    logStatus({
      actionDoing: 'Preparing to delete package.json and gitlab-ci.yml',
      subject: componentName,
    });
    await findPackageToDelete(componentName);
    await findGitlabToDelete(componentName);
  });
};
const main = async () => {
  cleanAllPJGL();
};
main();
