#!/usr/bin/env node

const Listr = require("listr");
const { program } = require("commander");
const chalk = require("chalk");
const prompts = require("prompts");
const path = require("path");
const figlet = require("figlet");
const package = require("./package.json");
const { copy, isPathInUse } = require("./helpers/copy");
const { install, initGit, checkPackageVersion } = require("./helpers/install");
const replace = require("./helpers/replace");

// Output path to create new portal app
let projectPath = "";


// Commander parameters to specify CLI behavior
program
  .name(package.name)
  .version(package.version)
  /**
   * TODO
   * Add Options
   * Add Example Options
   * Add templates
   */
  .arguments("[dir]")
  .usage(`${chalk.yellow("[dir]")}`)
  .description({
    dir: "Directory to be used on install Portal.js",
  })
  .action((name) => (projectPath = name))
  .option('--use-npm')
  .allowUnknownOption()
  .parse(process.argv);

// print a fancy Portal.js in the terminal
console.log(
  chalk.yellow(
    figlet.textSync('Portal.Js', {horizontalLayout: 'full'})
  )
);
/**
 * Method to ask a custon name if was not passed as parameter
 * returns the value passed from terminal input
 */
async function promptPath() {
  return prompts({
    type: "text",
    name: "path",
    message: "Choose a name to your project",
    initial: "",
    validate: (name) => {
      //TODO Method to validate valid path name
      return true;
    },
  });
}

/**
 * Main method to start CLI and validate inputs
 */
async function run() {
  if (typeof projectPath === "string") {
    projectPath = projectPath.trim();
  }
  if (!projectPath) {
    const response = await promptPath();
    if (typeof response.path === "string") {
      projectPath = response.path.trim();
    }
  }
  if (!projectPath) {
    //TODO separate log methods
    console.log();
    console.log("Please choose a name to your project:");
    console.log();
    console.log("Example:");
    console.log(
      `${chalk.cyan(program.name())} ${chalk.yellow("ny-portal-app")}`
    );
    console.log();

    process.exit(1);
  }

  const root = path.join(__dirname + "/../portal");

  const parsedPath = path.resolve(projectPath);
  const project = path.basename(parsedPath);

  console.log();
  console.log(
    `Begin Instalation of new portal.js on ${chalk.cyan(projectPath)} folder`
  );
  console.log();
  //TODO Move this method to another one to keep more functional and split responsabilites
  const tasks = new Listr([
    {
      title: "Fetching Content",
      task: () => copy(root, project),
    },
    {
      title: "Updating Content",
      task: () => "",
    },
    {
      title: "Installing Dependencies",
      task: () => install(project, true),
    },
    {
      title: "Git Init",
      task: () => initGit(projectPath),
    },
  ]);

  tasks.run().then(() => {
    console.log();
    console.log(`${chalk.greenBright("Instalation Completed!")}`);
    console.log();
    console.log(
      `Run ${chalk.cyan("cd " + projectPath)} and ${chalk.green(
        "yarn dev"
      )} or ${chalk.yellow("npm run dev")}`
    );
    console.log();
    console.log("Enjoy =)");
  });
}

//Main CLI execution workflow
run()
  .then(`${chalk.greenBright("Project Installed Sucess")}`)
  .catch((error) => {
    if (error.command) {
      console.log(`${chalk.cyan("Error on Create App")}`);
    } else {
      console.log(
        `${chalk.red("Unexpected Erro. Please report it as a bug")}`
      );
      console.log(error);
    }
    console.log();
    process.exit(1);
  });

@@ -621,91 +621,8 @@
 on)%0A
-  /**%0A   * TODO%0A   * Add Options%0A   * Add Example Options%0A   * Add templates%0A   */%0A
   .a
@@ -804,17 +804,17 @@
 .option(
-'
+%22
 --use-np
@@ -818,33 +818,9 @@
 -npm
-')%0A  .allowUnknownOption(
+%22
 )%0A  
@@ -846,148 +846,8 @@
 );%0A%0A
-// print a fancy Portal.js in the terminal%0Aconsole.log(%0A  chalk.yellow(%0A    figlet.textSync('Portal.Js', %7BhorizontalLayout: 'full'%7D)%0A  )%0A);%0A
 /**%0A
@@ -1144,49 +1144,221 @@
     
-//TODO Method to validate valid path name
+projectPath = name%0A      if(isPathInUse(projectPath))%7B%0A        return  %60$%7Bchalk.yellow(%0A        %22Path %22 +%0A          chalk.redBright(projectPath) +%0A          %22 is already in use and is not empty.%22%0A      )%7D%60%0A      %7D
 %0A   
@@ -1371,17 +1371,16 @@
 urn true
-;
 %0A    %7D,%0A

update prompt validate