package simulator.interfaces.html;

import models.algebra.Constant;
import models.algebra.Expression;
import models.algebra.Term;
import models.dataConstraintModel.JsonTerm;
import models.dataConstraintModel.MapTerm;
import simulator.Event;
import simulator.SystemState;
import simulator.interfaces.INativeReceiver;

public class HtmlElementTextReceiver implements INativeReceiver{
	
	protected HtmlElement element;
	private final IWebSocketMessageSender ws;
	
	public HtmlElementTextReceiver(HtmlElement elem, IWebSocketMessageSender ws) {
		this.ws = ws;
		element = elem;
	}

	@Override
	public void onReceiveFromModel(Event event, SystemState nextSystemState) {
		Expression message = event.getMessage();
		if (message instanceof Term) {
			Expression text = ((Term) message).getChild(0);
			if(text instanceof Constant) {
				element.setText(text.toString());
				
				JsonTerm json = new JsonTerm();
				json.addMember("\"method\"", new Constant("\"changeText\""));
				json.addMember("\"id\"", new Constant(element.getId()));
				MapTerm datas = new MapTerm();
				datas.insert("\"newText\"", new Constant(text.toString()));
				json.addMember("\"datas\"", datas);
				
				ws.send(json.toString());
			}
		}
	}

}
