import { removeFileExtension } from '../utils/fileHandlers';

/** generate a default image path based on authoring spec requirements
 *  general path looks like this
 *  articles/parent/media/fileDirectory/image.jpg
 *  [rootDirectory]/[media]/[curentFileBeingEdited]/[image]
 */
export function imageDefaultPath(path: string, imageName: string) {
	const paths = path.split('/');
	const directoryPath = paths.slice(0, -1).join('/');
	const fileName = paths.pop().split('.').slice(0, -1).join('');
	const directory = `${directoryPath}/media/${fileName}/${imageName}`;
	return directory.toLowerCase().replace(/[ ]/g, '-').replace(/[_]/g, '-');
}

/** This function takes a string and will check if
 *  this file name already exists. If so, it will try
 *  to append a number to the end of the file name.
 *  You can pass in an array of filenames to check.
 */
export function handleDuplicateFileName(filePath: string, pathsToCheck: string[]): string {
	if (pathsToCheck.find(pathToCheck => pathToCheck === filePath)) {
		const fileExtension = filePath.split('.').pop();
		const filePaths = filePath.split('/');
		let fileName = removeFileExtension(filePaths.pop().split('.').slice(0, -1).join(''));
		const numbersAtTheEndOfFileName = fileName.replace(/^\D+/, '');
		if (numbersAtTheEndOfFileName) {
			let incrementor = parseInt(numbersAtTheEndOfFileName);
			incrementor++;
			fileName = fileName.replace(numbersAtTheEndOfFileName, incrementor.toString());
			return handleDuplicateFileName(`${fileName}.${fileExtension}`, pathsToCheck);
		}
		return `${fileName}1.${fileExtension}`;
	}
	return filePath;
}
