package dev.kkorolyov.sqlob.construct.statement;

import java.util.LinkedList;
import java.util.List;

import dev.kkorolyov.sqlob.connection.DatabaseConnection;
import dev.kkorolyov.sqlob.construct.RowEntry;

/**
 * A SQL statement encapsulated as an executable command.
 */
public abstract class StatementCommand {
	private static final String parameterMarker = "\\?";
	
	private final String baseStatement;
	private final List<RowEntry> 	values,
																criteria;
	private final DatabaseConnection conn;

	StatementCommand(String baseStatement, List<RowEntry> values, List<RowEntry> criteria, DatabaseConnection conn) {
		this.baseStatement = baseStatement;
		this.values = values;
		this.criteria = criteria;
		this.conn = conn;
	}
	
	/** @return	base SQL statement */
	public String getBaseStatement() {
		return baseStatement;
	}
	
	/** @return statement values */
	public List<RowEntry> getValues() {
		return values;
	}
	/** @return statement criteria */
	public List<RowEntry> getCriteria() {
		return criteria;
	}
	/** @return all statement parameters in the order: {@code values}, {@code criteria}, or an empty list if this statement has no parameters */
	public List<RowEntry> getParameters() {
		List<RowEntry> parameters = new LinkedList<>();
		
		if (values != null) {
			for (RowEntry value : values)
				parameters.add(value);
		}
		if (criteria != null) {
			for (RowEntry criterion : criteria)
				parameters.add(criterion);
		}
		return parameters;
	}
	
	/** @return database connection registered to execute this statement */
	public DatabaseConnection getConn() {
		return conn;
	}
	
	@Override
	public String toString() {
		String result = baseStatement;
		
		for (RowEntry parameter : getParameters())
			result = result.replaceFirst(parameterMarker, parameter.getValue().toString());
		
		return result;
	}
}

@@ -1774,16 +1774,57 @@
 rMarker,
+ (parameter.getValue() == null ? %22NULL%22 :
  paramet
@@ -1848,16 +1848,17 @@
 tring())
+)
 ;%0A%09%09%0A%09%09r

Fix null issue in StatementCommand.toString()