package org.gcube.portlets.user.workspace.client.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.NumberFormat;

/**
 * The Class SizeUtil.
 *
 * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
 * 
 *         Nov 5, 2021
 */
public class SizeUtil {

	public static final NumberFormat numberFormat = NumberFormat.getFormat("#,##0.#");

	/**
	 * Readable file size.
	 *
	 * @param size the size
	 * @return the string
	 */
	public static String readableFileSize(long size) {
		GWT.log("Converting size: "+size);
		// -1 should be the size of a folder
		if (size == -1)
			return "";
		// in some cases the size returned by SHUB is negative, 
		// so reporting as 1B to user
		if (size < 0)
			return "1 byte";

		if (size == 0)
			return "0 byte";

		final String[] units = new String[] { "bytes", "kB", "MB", "GB", "TB" };
		int digitGroups = (int) (Math.log10(size) / Math.log10(1024));

		return numberFormat.format(size / Math.pow(1024, digitGroups)) +" " +units[digitGroups];

	}
}
