package simulator.interfaces.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import models.algebra.Constant;
import models.algebra.Expression;
import models.algebra.Term;
import models.dataConstraintModel.DataConstraintModel;
import models.dataConstraintModel.ResourcePath;
import models.dataFlowModel.DataTransferChannel;
import simulator.Resource;
import simulator.Simulator;
import simulator.interfaces.NativeSender;

public class ResultSender extends NativeSender{

	private String url;
	private String user;
	private String pass;
	
	public ResultSender(Simulator simulator, DataTransferChannel channel, ResourcePath resourcePath,
			Resource resource, String url, String user, String pass) {
		super(simulator, channel, resourcePath, resource);
		this.url = url;
		this.user = user;
		this.pass = pass;
	}
	
	public void executeQuery(String query) {
		StringBuilder resCSV = new StringBuilder();
		try(
			Connection conn = DriverManager.getConnection(url, user, pass);
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(query)
		){
			var meta = rs.getMetaData();
			for(int i = 1; i <= meta.getColumnCount(); i++) {
				resCSV.append(meta.getColumnName(i));
				if(i != meta.getColumnCount()) {
					resCSV.append(",");
				} else {
					resCSV.append("\n");
				}
			}
			while(rs.next()) {
				for(int i = 1; i <= meta.getColumnCount(); i++) {
					resCSV.append(rs.getString(i));
					if(i != meta.getColumnCount()) {
						resCSV.append(",");
					} else {
						resCSV.append("\n");
					}
				}
			}
		} catch(SQLException e) {
			resCSV.append("sql error");
			e.printStackTrace();
		}
		Constant res = new Constant(resCSV.toString(), DataConstraintModel.typeString);
		Expression message = channel.getOutputChannelMembers().iterator().next().getStateTransition().getMessageExpression();
		message = (Term) message.clone();
		((Term) message).setChild(0, res);
		sendToModel(message);
	}

}
