package simulator.interfaces.sql;

import models.algebra.Expression;
import models.algebra.Term;
import models.dataConstraintModel.ResourcePath;
import models.dataFlowModel.DataTransferChannel;
import simulator.Event;
import simulator.Resource;
import simulator.ResourceIdentifier;
import simulator.Simulator;
import simulator.SystemState;
import simulator.interfaces.INativeReceiver;

public class SQLPresenter implements INativeReceiver{

	
	public final String sendQueryChannelName = "sendQuery";
	public final String setResultChannelName = "setResult";
	
	protected Simulator simulator;
	
	protected DataTransferChannel sendQueryChannel;
	protected DataTransferChannel setResultChannel;
	
	public SQLPresenter(Simulator simulator) {
		this.simulator = simulator;
		sendQueryChannel = (DataTransferChannel) simulator.getModel().getChannel(sendQueryChannelName);
		setResultChannel = (DataTransferChannel) simulator.getModel().getInputChannel(setResultChannelName);
		simulator.addNativeReceiver(this, sendQueryChannel);
	}
	
	@Override
	public void onReceiveFromModel(Event event, SystemState nextSystemState) {
		Expression message = event.getMessage();
		ResourcePath path = event.getInputResourcePath();
		ResourceIdentifier ri = event.getResourceIdentifier(path);
		String dbUrl = ri.getPathParams().get(0).toString().replace("\"", "");
		if(message instanceof Term && ((Term) message).getChildren().size() >= 1) {
			Expression query = ((Term) message).getChild(0);
			System.out.println(simulator.getCurState());
			String user = simulator.getCurState().getResource("database." + dbUrl + ".user").getState().getValue().toString().replace("\"", "");
			String pass = simulator.getCurState().getResource("database." + dbUrl + ".password").getState().getValue().toString().replace("\"", "");
			
			System.out.println(user);
			System.out.println(pass);
			
			Resource sqlRes = nextSystemState.getResource(event.getInputResource().getResourceIdentifier());
			Resource resultRes = sqlRes.getParent().getChildrenMap().get("result");
			
			ResourcePath resPath = setResultChannel.getOutputResources().iterator().next();
			ResultSender sender = new ResultSender(simulator, setResultChannel, resPath, resultRes, dbUrl, user, pass);
			sender.executeQuery(query.toString().replace("\"", ""));
		}
	}
	
}
