package sharin.sql.formatter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class BasicSqlFormatter implements SqlFormatter {

    private final List<BasicFormatCommand> commandList = new ArrayList<BasicFormatCommand>();

    public BasicSqlFormatter(String template) {
        this(template, "'");
    }

    public BasicSqlFormatter(String template, String escapeChars) {
        int p = 0;
        int q = 0;
        int len = template.length();

        while (p < len) {
            q = template.indexOf('\n', p);

            if (q == -1) {
                q = len;
            }

            String line = template.substring(p, q);
            BasicFormatCommand command = new BasicFormatCommand(line,
                    escapeChars);
            commandList.add(command);
            p = q + 1;
        }
    }

    public String format(Object context) {

        if (context == null) {
            context = Collections.emptyMap();
        }

        BasicResultBuffer resultBuffer = new BasicResultBuffer();

        for (BasicFormatCommand command : commandList) {
            command.execute(context, resultBuffer);
        }

        return resultBuffer.getResult();
    }
}
