import path from 'path';
import fs from 'fs';

const getFolderAndFilename = (globalFilename: string) => {
  throwErrorIfPathNotExists(globalFilename);
  const array = globalFilename.split(path.sep);
  const name = array.pop();
  const folder = array.pop();
  return `../${folder}/${name}`;
};

const getFolderPath = (globalFilename: string) => {
  throwErrorIfPathNotExists(globalFilename);
  const folders = globalFilename.split(path.sep);
  let folderPath = '';
  for (let posArray = 0; posArray < folders.length - 2; posArray++) {
    folderPath += folders[posArray] + '/';
  }
  const lastFolder = folders[folders.length - 2];
  folderPath += lastFolder;
  return folderPath;
};

const throwErrorIfPathNotExists = (filePath: string) => {
  if (!fileExist(filePath)) {
    throw new Error('La dirección de archivo ' + filePath + ' no existe');
  }
};

const fileExist = (filePath: string) => {
  return fs.existsSync(filePath);
};

const createFile = (filePath: string) => {
  if (!fileExist(filePath)) {
    fs.mkdirSync(filePath);
  }
};

export default {
  getFolderAndFilename,
  getFolderPath,
  fileExist,
  createFile,
};