package eu.dnetlib.data.objectstore.filesystem;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

import eu.dnetlib.miscutils.collections.Pair;
import eu.dnetlib.miscutils.functional.xml.DnetXsltFunctions;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * The Class FileSystemUtility.
 *
 * @author sandro
 */
public class FileSystemUtility {

	private static final Log log = LogFactory.getLog(FileSystemUtility.class); // NOPMD by marko on 11/24/08 5:02 PM

	public static Pair<String, Long> saveAndGenerateMD5(final InputStream inputStream, final Path filePath) {
		if(inputStream==null) return null;

		String md5 = null;
		long size = 0;
		try {
			Files.copy(inputStream, filePath);

			FileInputStream fis = new FileInputStream(filePath.toFile());
			md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
			fis.close();
			size = Files.size(filePath);

		} catch (IOException e1) {
			log.error(e1);
		}

		return new Pair<String, Long>(md5, size);
	}

	/**
	 * Delete folder recursive.
	 *
	 * @param path the path
	 * @return true, if successful
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public static boolean deleteFolderRecursive(final Path path) throws IOException {

		Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
				Files.delete(file);
				return FileVisitResult.CONTINUE;
			}

			@Override
			public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
				Files.delete(dir);
				return FileVisitResult.CONTINUE;
			}
		});
		return true;
	}

	public static Path objectStoreFilePath(final String basePath, final String objectStoreId, final String objectIdentifier) {
		final Path baseDirPath = FileSystems.getDefault().getPath(basePath).resolve(objectStoreId);
		final String md5id = DnetXsltFunctions.md5(objectIdentifier);
		final String firstLevel = StringUtils.substring(md5id, 0, 2);
		final String secondLevel = StringUtils.substring(md5id, 2, 4);
		final String fileName = StringUtils.substring(md5id, 4) + ".obj";
		return baseDirPath.resolve(firstLevel).resolve(secondLevel).resolve(fileName);
	}

}
