001/*******************************************************************************
002 * Crown Copyright (c) 2006 - 2014, Copyright (c) 2006 - 2014 Kestral Computing P/L.
003 * All rights reserved. This program and the accompanying materials
004 * are made available under the terms of the Eclipse Public License v1.0
005 * which accompanies this distribution, and is available at
006 * http://www.eclipse.org/legal/epl-v10.html
007 * 
008 * Contributors:
009 *    Kestral Computing P/L - initial implementation
010 *******************************************************************************/
011
012package org.fhir.ucum;
013
014public class FormalStructureComposer {
015
016        public String compose(Term term) {
017                StringBuilder bldr = new StringBuilder();
018                composeTerm(bldr, term);
019                return bldr.toString();
020        }
021
022        private void composeTerm(StringBuilder bldr, Term term) {
023                if (term.getComp() != null)
024                        composeComp(bldr, term.getComp());
025                if (term.getOp() != null)
026                        composeOp(bldr, term.getOp());
027                if (term.getTerm() != null) { 
028//                      bldr.append('(');
029                        composeTerm(bldr, term.getTerm());              
030//                      bldr.append('}');
031                }
032        }
033
034        private void composeComp(StringBuilder bldr, Component comp) {
035                if (comp instanceof Factor)
036                        composeFactor(bldr, (Factor)comp);
037                else if (comp instanceof Symbol)
038                        composeSymbol(bldr, (Symbol)comp);
039                else if (comp instanceof Term)
040                        composeTerm(bldr, (Term)comp);
041                else
042                        bldr.append('?');
043        }
044
045        private void composeSymbol(StringBuilder bldr, Symbol symbol) {
046                bldr.append('(');
047                if (symbol.getPrefix() != null) { 
048                        bldr.append(symbol.getPrefix().getNames().get(0));
049                }
050                bldr.append(symbol.getUnit().getNames().get(0));
051                if (symbol.getExponent() != 1) { 
052                        bldr.append(" ^ ");
053                        bldr.append(symbol.getExponent());
054                }
055                bldr.append(')');
056        }
057
058        private void composeFactor(StringBuilder bldr, Factor comp) {
059           bldr.append(comp.getValue());                
060        }
061
062        private void composeOp(StringBuilder bldr, Operator op) {
063                if (op == Operator.DIVISION)
064                        bldr.append(" / ");
065                else
066                        bldr.append(" * ");
067        }
068
069}