package org.wikiwebserver.sync.gui;

import java.awt.Component;
import java.text.DecimalFormat;

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class FileSizeCellRenderer extends DefaultTableCellRenderer {
    
    private static final long serialVersionUID = 1L;

    public FileSizeCellRenderer() {
    }

    public Component getTableCellRendererComponent(JTable table, Object obj, 
            boolean isSelected, boolean hasFocus, int row, int column) {
    
        setValue(formatSize((Long)obj));
        
        return this;
    }
    

    public static String formatSize(long bytes) {
        
        if (bytes == 1) return "1 byte";
        
        int suffixIdx = 0;
        double reducedBytes = (double) bytes;
        while (reducedBytes >= 1024.0) {
            suffixIdx++;
            reducedBytes /= 1024.0;
        }
        
        String formatString = bytes >= 1024 ? "0.00" : "0";
        DecimalFormat df = new DecimalFormat(formatString);
        return df.format(reducedBytes) + " " + SIZE_SUFFIX[suffixIdx];
    }
    
    private static final String[] SIZE_SUFFIX = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB" };     
}

