package uk.me.nxg.unity;

class UnitWriterDebugging extends UnitWriter {

    java.text.DecimalFormat df;

    public UnitWriterDebugging(UnitExpr ue) {
        super(ue);
        // Force the formatting of numbers to be in the US locale (ie
        // we get '.' not ',' as the decimal separator); this makes
        // the test locale-independent.
        df = new java.text.DecimalFormat("0.000", // always three decimal digits
                                         new java.text.DecimalFormatSymbols(java.util.Locale.US));
    }

    public String write() {
        return write(true);
    }

    // This mechanism for suppressing the leading factor is for the
    // benefit of FunctionOfUnit.toDebugString()
    public String write(boolean includeFactor) {
        boolean first = true;
        StringBuilder sb = new StringBuilder();

        if (includeFactor) {
            double lfact = ue.getLogFactor();
            if (lfact == Math.floor(lfact)) {            
                sb.append(String.format("%d", Math.round(ue.getLogFactor())));
            } else {
                sb.append(df.format(ue.getLogFactor()));
            }
            first = false;
        }
        
        java.util.Iterator<OneUnit> i = ue.sortedIterator();
        while (i.hasNext()) {
            if (first)
                first = false;
            else
                sb.append(' ');
            sb.append(i.next().toDebugString());
        }
        return sb.toString();
    }

    void writeNumber(StringBuilder sb, double d) {
        writeNumber(sb, d, false, false, false, false);
    }
}
