import * as plugins from './mod.plugins.js';
import * as paths from '../paths.js';
import * as gulpFunction from '@push.rocks/gulp-function';
import { Project } from '../classes.project.js';

/**
 * runs the npmextra file checking
 */
export const run = async (projectArg: Project) => {
  const formatSmartstream = new plugins.smartstream.StreamWrapper([
    plugins.smartgulp.src([`npmextra.json`]),
    gulpFunction.forEach(async (fileArg: plugins.smartfile.SmartFile) => {
      const fileString = fileArg.contents.toString();
      const npmextraJson = JSON.parse(fileString);

      if (!npmextraJson.gitzone) {
        npmextraJson.gitzone = {};
      }

      const expectedRepoInformation: string[] = [
        'projectType',
        'module.githost',
        'module.gitscope',
        'module.gitrepo',
        'module.description',
        'module.npmPackagename',
        'module.license',
      ];

      const interactInstance = new plugins.smartinteract.SmartInteract();
      for (const expectedRepoInformationItem of expectedRepoInformation) {
        if (!plugins.smartobject.smartGet(npmextraJson.gitzone, expectedRepoInformationItem)) {
          interactInstance.addQuestions([
            {
              message: `What is the value of ${expectedRepoInformationItem}`,
              name: expectedRepoInformationItem,
              type: 'input',
              default: 'undefined variable',
            },
          ]);
        }
      }

      const answerbucket = await interactInstance.runQueue();
      for (const expectedRepoInformationItem of expectedRepoInformation) {
        const cliProvidedValue = answerbucket.getAnswerFor(expectedRepoInformationItem);
        if (cliProvidedValue) {
          plugins.smartobject.smartAdd(
            npmextraJson.gitzone,
            expectedRepoInformationItem,
            cliProvidedValue,
          );
        }
      }

      // delete obsolete
      // tbd

      if (!npmextraJson.npmci) {
        npmextraJson.npmci = {};
      }

      fileArg.setContentsFromString(JSON.stringify(npmextraJson, null, 2));
    }),
    plugins.smartgulp.replace(),
  ]);
  await formatSmartstream.run().catch((error) => {
    console.log(error);
  });
};