package uk.me.nxg.unity;

/**
 * Produce LaTeX output, using the siunitx package.
 */
class UnitWriterLaTeX extends UnitWriter {

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

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

        try {
            sb.append("\\si{");
            if (ue.getLogFactor() != 0.0) {
                writeNumber(sb, Math.pow(10,ue.getLogFactor()));
            }

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

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