/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.text;

import java.io.IOException;
import net.ranides.assira.text.PrintPatternFactory.Token;

/**
 *
 * @author ranides
 * @todo (migration) assira (printf)
 */
public class PrintPattern {
    
    private final Token[] tokens;

    @SuppressWarnings("PMD.ArrayIsStoredDirectly")
    PrintPattern(Token[] tokens) {
        this.tokens = tokens;
    }
    
    public Appendable formatTo(Appendable target, Object... arguments) throws IOException {
        for(Token token : tokens) {
            token.apply(target, arguments);
        }
        return target;
    }
    
    public StringBuilder formatTo(StringBuilder target, Object... arguments) {
        try {
            for(Token token : tokens) {
                token.apply(target, arguments);
            }
            return target;
        } catch (IOException cause) {
            throw new AssertionError(cause);
        }
    }
    
    public StringBuffer formatTo(StringBuffer target, Object... arguments) throws IOException {
        try {
            for(Token token : tokens) {
                token.apply(target, arguments);
            }
            return target;
        } catch (IOException cause) {
            throw new AssertionError(cause);
        }
    }
    
    public String format(Object... arguments) {
        return formatTo(new StringBuilder(estimate(arguments)), arguments).toString();
    }
    
    public int estimate(Object[] arguments) {
        int size = 0;
        for(Token token : tokens) {
            size += token.estimate(arguments);
        }
        return size;
    }

}
