package simulator.interfaces.swing;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

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 ComponentTextSender extends NativeSender implements DocumentListener {

	public ComponentTextSender(Simulator simulator, DataTransferChannel channel, ResourcePath resourcePath, Resource resource) {
		super(simulator, channel, resourcePath, resource);
	}

	@Override
	public void insertUpdate(DocumentEvent e) {
		Document d = e.getDocument();
		try {
			Constant text = new Constant(d.getText(0, d.getLength()), DataConstraintModel.typeString);
			Expression message = channel.getOutputChannelMembers().iterator().next().getStateTransition().getMessageExpression();
			message = (Term) message.clone();
			((Term) message).setChild(0, text);
			sendToModel(message);
		} catch (BadLocationException e1) {
			e1.printStackTrace();
		}
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		Document d = e.getDocument();
		try {
			Constant text = new Constant(d.getText(0, d.getLength()), DataConstraintModel.typeString);
			Expression message = channel.getOutputChannelMembers().iterator().next().getStateTransition().getMessageExpression();
			message = (Term) message.clone();
			((Term) message).setChild(0, text);
			sendToModel(message);
		} catch (BadLocationException e1) {
			e1.printStackTrace();
		}
	}

	@Override
	public void changedUpdate(DocumentEvent e) {
		Document d = e.getDocument();
		try {
			Constant text = new Constant(d.getText(0, d.getLength()), DataConstraintModel.typeString);
			Expression message = channel.getOutputChannelMembers().iterator().next().getStateTransition().getMessageExpression();
			message = (Term) message.clone();
			((Term) message).setChild(0, text);
			sendToModel(message);
		} catch (BadLocationException e1) {
			e1.printStackTrace();
		}
	}

}
