/* eslint-disable */
// @ts-nocheck
const dotenv = require('dotenv');
const path = require('path');
const fs = require('fs');
const exec = require('child_process').exec;
const clients = require('./yamlsList').clients

let envName = '.env';

if (process.env.NODE_ENV) {
  envName += `.${process.env.NODE_ENV}`;
}

dotenv.config({ path: path.join(__dirname, '../', envName) });

const fullPath = path.join(__dirname, '../', 'src/openapi');
const ervuFullPath = path.join(__dirname, '../', 'src/recruits/openapi');

function clearAll(localPath = fullPath, noLogging = false) {
  if (fs.existsSync(localPath)) {
    if (!noLogging) {
      console.group();
      console.log('Clearing all...');
    }

    const errors = [];

    fs.readdirSync(localPath).forEach((file) => {
      const currentPath = path.join(localPath, file);

      if (fs.lstatSync(currentPath).isDirectory()) {
        clearAll(currentPath, true);
      } else {
        try {
          fs.unlinkSync(currentPath);
        } catch (e) {
          errors.push(e);
        }
      }
    });

    if (localPath !== fullPath) {
      try {
        fs.rmdirSync(localPath);
      } catch (e) {
        errors.push(e);
      }
    }

    if (!noLogging) {
      if (errors.length) {
        errors.forEach((e) => console.error('ERROR:', e.message));
      } else {
        console.log('SUCCESS');
      }
    }

    console.groupEnd();
  }
}

function generateAll() {
  if (clients.size) {
    if (fs.existsSync(fullPath)) {
      console.group();
      console.log('Generating all...');

      const commands = [];

      clients.forEach((value, key) => {
        const currentPath = path.join(fullPath, key);
        const command = `openapi-generator-cli generate -i ${value} -g typescript-axios -o ${currentPath} && npx replace-in-file "// tslint:disable" "/* eslint-disable */ // @ts-nocheck" ${currentPath}/*`;
        commands.push(command);
      });

      asyncExec(commands.join(' && '))
        .then(() => {
          console.log('SUCCESS');
        })
        .catch((e) => {
          console.error('ERROR:', e.message);
        })
        .finally(() => {
          console.groupEnd();
        });
    }
  }
}

/**
 Функция генерации только определенных путей.
 Данные для генерации берутся из переменной process.env.npm_config_clients
 Команда запуска npm run generatePaths --clients=mz-resend,idm
 Параметры --clients строкой через запятую
 **/
const generate = () => {
  if (fs.existsSync(fullPath)) {
    try {
      const inputClients = process.env.npm_config_clients.split(",");
      console.group('Generating paths ...', inputClients);
      const commands = [];
      inputClients.forEach((name) => {
        if (clients.get(name)) {
          // Проверяем является ли ресурс ссылкой
          let resource = '';
          if (clients.get(name).match(/^http:\/\//)) {
            resource = clients.get(name)
          } else {
            resource = `'./init/${clients.get(name)}'`
          }

          const currentPath = path.join(fullPath, name);
          const command = `
          openapi-generator-cli generate -i ${resource} -g typescript-axios -o ${currentPath} && npx replace-in-file "// tslint:disable" "/* eslint-disable */ // @ts-nocheck" ${currentPath}/*`;
          commands.push(command);
        }
      });
      if (commands.length) {
        asyncExec(commands.join(" && "))
            .then((response) => {
              console.log(response);
              console.log('SUCCESS');
            })
            .catch((e) => {
              console.error('ERROR:', e.message);
            })
            .finally(() => {
              console.groupEnd();
            });
      } else {
        console.log('not commands');
      }
    } catch (e) {
      console.log('ERROR generate: ', e);
    }
  }
};

const ervuGenerate = () => {
  if (fs.existsSync(ervuFullPath)) {
    try {
      const command = `openapi-generator-cli generate -i './init/ervu-service.yaml' -g typescript-axios -o './src/recruits/openapi/ervu-service' --global-property skipFormModel=false --type-mappings object=any --additional-properties=withSeparateModelsAndApi=true,modelPackage='models',apiPackage='api',supportsES6=true`;
      asyncExec(command)
        .then((response) => {
          console.log(response);
          console.log('SUCCESS');
        })
        .catch((e) => {
          console.error('ERROR:', e.message);
        })
        .finally(() => {
          console.log('FINISH');
        });
    } catch (e) {
      console.log('ERROR generate: ', e);
    }
  }
};

function asyncExec(command) {
  return new Promise((resolve, reject) => {
    exec(command, (error, stdout, stderr) => {
      if (error) {
        return reject(error);
      }

      return resolve(stdout ? stdout : stderr);
    });
  });
}

module.exports.clearAll = clearAll;

module.exports.generateAll = generateAll;

module.exports.generate = generate;

module.exports.ervuGenerate = ervuGenerate;
