
package de.ivu.elect.business.datei.entity;

import static org.apache.commons.lang3.StringUtils.substringAfterLast;

import java.io.File;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Locale;

import javax.inject.Inject;

import de.ivu.elect.jee.faces.UserLocale;

public class FileMetaFormatter {

  private static final long BYTES_PER_KILOBYTE = BinaryUnit.bytesOf(1, BinaryUnit.KILOBYTE);

  private static final long BYTES_PER_MEGABYTE = BinaryUnit.bytesOf(1, BinaryUnit.MEGABYTE);

  private static final long BYTES_PER_GIGABYTE = BinaryUnit.bytesOf(1, BinaryUnit.GIGABYTE);

  @Inject
  private transient UserLocale userLocale;

  public FileMetaFormatter() {
    super();
  }

  private String getFileName(File file) {
    return file.getName();
  }

  public String getFileExtension(File file) {
    return getFileExtension(getFileName(file));
  }

  public String getFileExtension(String fileName) {
    return substringAfterLast(fileName, ".");
  }

  public String getFileSize(File file) {
    return getFileSize(file.length(), userLocale.getLocale());
  }

  public String getFileSize(File file, Locale locale) {
    return getFileSize(file.length(), locale);
  }

  public String getFileSize(double fileSizeInBytes) {
    return getFileSize(fileSizeInBytes, userLocale.getLocale());
  }

  public String getFileSize(double fileSizeInBytes, Locale locale) {
    if (fileSizeInBytes > 0) {
      long divisor = BYTES_PER_KILOBYTE;
      String symbol = BinaryUnit.KILOBYTE.getSymbol();
      int fractionDigits = 2;

      if (fileSizeInBytes < 10) {
        fractionDigits = 3;
      }

      if (fileSizeInBytes >= BYTES_PER_MEGABYTE) {
        divisor = BYTES_PER_MEGABYTE;
        symbol = BinaryUnit.MEGABYTE.getSymbol();
      }

      if (fileSizeInBytes >= BYTES_PER_GIGABYTE) {
        divisor = BYTES_PER_GIGABYTE;
        symbol = BinaryUnit.GIGABYTE.getSymbol();
      }

      NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
      numberFormat.setRoundingMode(RoundingMode.DOWN);
      numberFormat.setMinimumFractionDigits(fractionDigits);
      numberFormat.setMaximumFractionDigits(fractionDigits);

      return String.format("%s %s", numberFormat.format(fileSizeInBytes / divisor), symbol);
    }

    return "";
  }
}
