const childProcess = require('child_process');
const execSync = childProcess.execSync;
const fs = require('fs');
const fse = require('fs-extra');
const glob = require('glob');
const path = require('path');
const figlet = require('figlet');

module.exports.getAngularPath = (targetPath, appName, appType, artifactId) => {
  switch(appType) {
    case 'angular':
    case 'mobile':
      return targetPath;
    case 'web-maven':
      return `${targetPath}/src/main/angular`;
    case 'web-spring-boot':
      return `${targetPath}/${artifactId}-web/src/main/angular`;
    case 'web-symfony':
      return `${targetPath}/client`;
  }
}

module.exports.getArgs = () => {
  const argv = require('yargs').argv;

  const processArgs = process.env._CSDR_ARGS;

  let args = {};

  if (processArgs) {
    processArgs.split(',').forEach((item) => {
      // check if it's defined as array - example format : someArray:test1=test1|test2=test2
      if (item.indexOf('Array') > 0) {
        const arrayItems = item.split(':')[1];
        const subItems = arrayItems.split('|');
        const array = [];
        subItems.forEach((sub) => {
          const subItemSplit = sub.split('=');
          const newItem = {};
          newItem[subItemSplit[0].trim()] = subItemSplit[1].trim();
          array.push(newItem);
        })
        args[item.split(':')[0]] = array;

      // otherwise normal key/value pairs - example format : test1:test1,test2:test2
      } else {
        const itemSplit = item.split(':');
        args[itemSplit[0].trim()] = itemSplit[1].trim();
      }
    })
  }

  return {
    root: argv._[0],
    ...argv,
    ...args
  }
}


module.exports.logBigTitle = (text) => {
  console.log('\n\n');
  console.log('\x1b[33m', figlet.textSync(text, { horizontalLayout: 'full' }) ,'\x1b[0m');
  console.log('\n');
}

module.exports.logTitle = (msg) => {
  log(msg, 0);
}

const logInfo = module.exports.logInfo = (msg) => {
  log(msg, 1);
}

module.exports.logSuccess = (msg) => {
  if (!msg) msg = 'OK';
  log(msg, 2);
}

module.exports.logError = (msg) => {
  log(msg, 3);
}
module.exports.logErrorTrace = (filename, method, e) => {
  log(`ERROR in ${filename}`, 3);
  log(`...method : ${method}`, 3);
  log(`...message : ${e.message}`, 3);
}

module.exports.logWarning = (msg) => {
  log(msg, 4);
}

module.exports.logAccent = (msg) => {
  log(msg, 5);
}

module.exports.logBanner = (msg) => {
  log(msg, 6);
}

module.exports.logDebug = (msg) => {
  if (getArgs().debug) {
    log(msg, 7);
  }
}
module.exports.logDebugTrace = (filename, method, e) => {
  if (getArgs().debug) {
    log(`ERROR in ${filename}`, 7);
    log(`...method : ${method}`, 7);
    log(`...message : ${e.message}`, 7);
  }
}
module.exports.logDebugResponse = (response) => {
  if (getArgs().debug) {
    console.log(response);
  }
}

module.exports.isDirEmpty = (path) => {
  try {
    var files = fse.readdirSync(path);

    if (files.length === 0) {
      return true;
    } else {
      return false;
    }

  } catch (err) {
    return false;
  }
}

const isFileExists = module.exports.isFileExists = (path) => {
  try {
      return fs.statSync(path);
  } catch (err) {
      return false;
  }
}


module.exports.mkdir = (path) => {
  if (!fs.existsSync(path)) {
      fs.mkdirSync(path);
  }
}

module.exports.copydir = (from, to, overwrite = true, globPattern = '**/*') => {
  function _recursiveMkDir(dir) {
    if (!fs.existsSync(dir)) {
        _recursiveMkDir(path.dirname(dir));
        fs.mkdirSync(dir);
    }
  }
  
  logInfo('----->copydir from : ' + from + ' ====> to : ' + to );
  var files = glob.sync(globPattern, { cwd: from, nodir: true, follow: true, dot: true });
  files.forEach(file => {
      const origin = path.join(from, file);
      const dest = path.join(to, file);
      _recursiveMkDir(path.dirname(dest));
      fse.copySync(origin, dest, { overwrite: overwrite });
  });
}

module.exports.move = (from, to) => {
    fse.removeSync(to);
    fse.moveSync(from, to, );
}

module.exports.remove = (path) => {
  fse.removeSync(path);
}

module.exports.copy = (origin, dest) => {
  fse.copySync(origin, dest);
}

const log = (msg, type) => {
  var msgContent;

  if (type === 0 || !type) {
      msgContent = `\n${msg.toUpperCase()}`;
      console.info('\x1b[33m', msgContent ,'\x1b[0m');
  }
  if (type === 1) {
      msgContent = `${msg}`;
      console.info('\x1b[34m\x1b[1m', msgContent ,'\x1b[0m');
  }
  if (type === 2) {
      msgContent = `${msg}\n`;
      console.info('\x1b[32m\x1b[1m', msgContent ,'\x1b[0m');
  }
  if (type === 3) {
      msgContent = `\n${msg}`;
      console.info('\x1b[31m\x1b[1m', msgContent ,'\x1b[0m');
  }
  if (type === 4) {
      msgContent = `\n${msg}\n`;
      console.info('\x1b[33m', msgContent ,'\x1b[0m');
  }
  if (type === 5) {
      msgContent = `${msg}\n`;
      console.info(msgContent);
  }
  if (type === 6) {
      msgContent = msg
      console.info('\n\n');
      console.info(msgContent);
      console.info('\n');
  }
  if (type === 7) {
    msgContent = `${msg}`;
    console.info(msgContent);
  }
}