package simulator.interfaces.rest;

import models.algebra.Expression;
import models.algebra.Term;
import models.dataConstraintModel.JsonTerm;
import models.dataConstraintModel.MapTerm;
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 RestPresenter implements INativeReceiver{
	
	public final String changeStateChannelName = "changeState";
	public final String setResponseChannelName = "setResponse";
	
	protected Simulator simulator;
	
	protected DataTransferChannel changeStateChannel;
	protected DataTransferChannel setResponseChannel;
	
	public RestPresenter(Simulator simulator) {
		this.simulator = simulator;
		changeStateChannel = (DataTransferChannel) simulator.getModel().getChannel(changeStateChannelName);
		setResponseChannel = (DataTransferChannel) simulator.getModel().getInputChannel(setResponseChannelName);
		simulator.addNativeReceiver(this, changeStateChannel);
	}

	@Override
	public void onReceiveFromModel(Event event, SystemState nextSystemState) {
		Expression message = event.getMessage();
		ResourcePath path = event.getInputResourcePath();
		ResourceIdentifier ri = event.getInputResourceIdentifier(path);
		System.out.println(path);
		System.out.println(ri);
		String clientNumber = ri.getPathParams().get(0).toString();
		if(message instanceof Term && ((Term) message).getChildren().size() >= 1) {
			Expression state = ((Term) message).getChild(0);
			System.out.println(state);
			if (state.toString().equals("1")) {
				String url = simulator.getCurState().getResource("restClients." + clientNumber + ".url").getState().getValue().toString().replace("\"", "");
				String method = simulator.getCurState().getResource("restClients." + clientNumber + ".method").getState().getValue().toString();
//				MapTerm header = (MapTerm)simulator.getCurState().getResource("restClients." + clientNumber + ".header").getState().getValue();
//				JsonTerm body = (JsonTerm)simulator.getCurState().getResource("restClients." + clientNumber + ".body").getState().getValue();
				MapTerm header = new MapTerm();
				JsonTerm body = new JsonTerm();
				
				Resource stateRes = nextSystemState.getResource(event.getInputResource().getResourceIdentifier());
				Resource responseRes = stateRes.getParent().getChildrenMap().get("response");
				System.out.println(responseRes.getResourceIdentifier());
				
				ResourcePath resPath = setResponseChannel.getOutputResources().iterator().next();
				ResponseSender sender = new ResponseSender(simulator, setResponseChannel, resPath, responseRes, url, method, header, body);
				sender.sendRequest();
			}
		}
	}

}
