package org.aktin.broker.query.sql;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.function.Function;

import javax.sql.DataSource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import org.aktin.broker.query.QueryHandler;
import org.aktin.broker.query.QueryHandlerFactory;
import org.w3c.dom.Element;

// TODO add qualifier annotation

public class SQLHandlerFactory implements QueryHandlerFactory{
	private DataSource ds;
	private Charset exportCharset;

	public SQLHandlerFactory(DataSource database) {
		this.ds = database;
		this.exportCharset = StandardCharsets.UTF_8;
	}

	public Charset getExportCharset(){
		return exportCharset;
	}

	Connection openConnection() throws SQLException{
		return ds.getConnection();
	}
	@Override
	public String getElementName() {
		return SQLQuery.XML_ELEMENT;
	}

	@Override
	public String getNamespace() {
		return SQLQuery.XML_NAMESPACE;
	}

	@Override
	public QueryHandler parse(Element element, Function<String,String> propertyLookup) {
		SQLQuery q;
		try {
			JAXBContext c = JAXBContext.newInstance(SQLQuery.class);
			q = (SQLQuery)c.createUnmarshaller().unmarshal(element);
		} catch (JAXBException e) {
			throw new IllegalArgumentException("Unable to parse query XML", e);
		}
		return wrap(q, propertyLookup);
	}

	public SQLHandler wrap(SQLQuery query, Function<String,String> propertyLookup){
		return new SQLHandler(this, query, propertyLookup);
	}

}

@@ -159,24 +159,50 @@
 LException;%0A
+import java.util.Objects;%0A
 import java.
@@ -332,52 +332,8 @@
 n;%0A%0A
-import org.aktin.broker.query.QueryHandler;%0A
 impo
@@ -562,16 +562,96 @@
 arset;%0A%0A
+%09public SQLHandlerFactory() %7B%0A%09%09this.exportCharset = StandardCharsets.UTF_8;%0A%09%7D%0A
 %09public 
@@ -687,24 +687,34 @@
 database) %7B%0A
+%09%09this();%0A
 %09%09this.ds = 
@@ -728,58 +728,87 @@
 e;%0A%09
-%09this.exportCharset = StandardCharsets.UTF_8
+%7D%0A%09%0A%0A%09public void setDataSource(DataSource database)%7B%0A%09%09this.ds = database
 ;%0A%09%7D%0A
-%0A
 %09pub
@@ -917,16 +917,68 @@
 eption%7B%0A
+%09%09Objects.requireNonNull(ds, %22datasource not set%22);%0A
 %09%09return
@@ -1180,21 +1180,19 @@
 %09public 
-Query
+SQL
 Handler 

allow empty constructor. cleanup.