import { dirname } from "path";
import { fileURLToPath } from "url";
import { outputFile } from "fs-extra";

const componentName = process.argv[2];
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Note for later use //
// To use this script :
// yarn nc <folderName>/<componentName>
// Exemple : "yarn nc components/MyComponent" will create
// a folder MyComponent (and all the basic) within the components folder

function lowerCaseFirstLetter(string) {
  return string.charAt(0).toLowerCase() + string.slice(1);
}

function returnComponentPath(cpt, fileType) {
  if (cpt.includes("/")) {
    const pathName = cpt.split("/")[0];
    const component = cpt.split("/")[1];
    return `${pathName}/${component}/${fileType}`;
  }
  return `${cpt}/${fileType}`;
}

function checkComponentName(cpt) {
  if (cpt.includes("/")) {
    return cpt.split("/")[1];
  }
  return cpt;
}

// Create the default index.js file
outputFile(
  `${__dirname}/../src/${returnComponentPath(componentName, "index.js")}`,
  `import './styles.css';

const ${checkComponentName(componentName)} = () => {
  return <div className="${lowerCaseFirstLetter(
    checkComponentName(componentName)
  )}"></div>;
};

export default ${checkComponentName(componentName)};`,
  function (err) {
    if (err) {
      return console.log(err);
    }
    // Create the default styles.css file
    outputFile(
      `${__dirname}/../src/${returnComponentPath(componentName, "styles.css")}`,
      `.${lowerCaseFirstLetter(checkComponentName(componentName))} {}`,
      function (err) {
        if (err) {
          return console.log(err);
        }
        console.log("The file was saved!");
      }
    );
  }
);
