package uk.me.nxg.unity;

class UnitWriterOgip extends UnitWriter {

    public UnitWriterOgip(UnitExpr ue) {
        super(ue);
    }

    public String write() {
        StringBuilder sb = new StringBuilder();
        boolean first = true;

        try {
            if (ue.getLogFactor() != 0.0) {
                sb.append("10**");
                writeNumber(sb, ue.getLogFactor());
                first = false;
            }
            for (OneUnit u : ue) {
                if (first) {
                    first = false;
                } else {
                    sb.append(' ');
                }
                double e = u.getExponent();
                if (e == 1.0) {
                    sb.append(u.unitString(Syntax.OGIP));
                } else if (e < 0.0) {
                    sb.append('/').append(u.unitString(Syntax.OGIP));
                    if (e != -1.0) {
                        sb.append("**");
                        writeNumber(sb, -e);
                    }
                } else {
                    // e is positive and not 1.0
                    sb.append(u.unitString(Syntax.OGIP)).append("**");
                    writeNumber(sb, e);
                }
            }
            return sb.toString();
        } catch (UnitParserException e) {
            throw new AssertionError("units system failed to recognise built-in syntax OGIP: " + e);
        }
    }

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