/* UtilLib - Copyright (c) 2007-2014 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.sql;

import java.io.IOException;
import java.io.Writer;
import net.mapeadores.util.primitives.Decimal;


/**
 *
 * @author Vincent Calame
 */
public class InsertWriter {

    private final Writer writer;
    private boolean firstField = true;
    private String defaultString = "";

    public InsertWriter(Writer writer) {
        this.writer = writer;
    }

    public void setDefaultString(String defaultString) {
        this.defaultString = defaultString;
    }

    public void startInsert(String tableName) throws IOException {
        writer.write("INSERT INTO ");
        writer.write(tableName);
        writer.write(" VALUES(");
        firstField = true;
    }

    public void endInsert() throws IOException {
        writer.write(")");
    }

    public void endLine() throws IOException {
        writer.write(";\n");
    }

    public void endInsertLine() throws IOException {
        endInsert();
        endLine();
    }

    public void addInteger(long lg) throws IOException {
        testFirstField();
        writer.write(String.valueOf(lg));
    }

    public void addDouble(double d) throws IOException {
        testFirstField();
        writer.write(String.valueOf(d));
    }

    public void addDecimal(Decimal decimal) throws IOException {
        testFirstField();
        writer.write(decimal.toString());
    }

    public void addText(CharSequence charSequence) throws IOException {
        testFirstField();
        if (charSequence == null) {
            writer.write("NULL");
        } else {
            writer.write('\'');
            int length = charSequence.length();
            for (int i = 0; i < length; i++) {
                char carac = charSequence.charAt(i);
                if (carac == '\'') {
                    writer.write("''");
                } else if (carac == '\\') {
                    writer.write("\\\\");
                } else {
                    writer.write(carac);
                }
            }
            writer.write('\'');
        }
    }

    public void addNull() throws IOException {
        testFirstField();
        writer.write("NULL");
    }

    public void addNull(int length) throws IOException {
        for (int i = 0; i < length; i++) {
            addNull();
        }
    }

    public void addDefaultString(int length) throws IOException {
        for (int i = 0; i < length; i++) {
            addText(defaultString);
        }
    }

    private void testFirstField() throws IOException {
        if (firstField) {
            firstField = false;
        } else {
            writer.write(",");
        }
    }

}
