import JSim.util.*;
import JSim.data.*;
import JSim.project.*;
import JSim.aserver.*;
import JSim.text.VarQuery;
import JSim.gui.plugin.GGraphic;

import java.awt.*;
import javax.swing.*;
import org.w3c.dom.Element;

public class MyConstraints extends GGraphic {
	private JTextArea jtext;
	private JScrollPane jscroll;
	private PModel pmodel;

	// constructor
	public MyConstraints(GGraphic.Callbacks cb) throws Exception {
	    super(cb);
	    jtext = new JTextArea();
	    jscroll = new JScrollPane(jtext);
	    refresh();
	}

	// query 
	public JComponent getJComponent() { return jscroll; }
	
	// import state via XML
	public void importXML(Element e) {
	    pmodel = null;
	    if (e == null) {
		pmodel = callbacks().userModelSelect(jscroll);
	    } else {
		String name = e.getAttribute("modelName");
		PNamed p = callbacks().getProject().child(name);
		if (p instanceof PModel)
		    pmodel = (PModel) p;
	    }    
	    refresh();
	}

	// export state via XML
	public void exportXML(Element e) {
	    e.setAttribute("modelName", 
	    	(pmodel == null) ? "" : pmodel.name());
	}

	// model job control
	public void jobStarted(PJob pjob) {
	    refresh();
	}   
	public void jobStopped(PJob pjob) {
	    if (pmodel == null) return;
	    if (pjob.pmodel() != pmodel) return;
	    if (pjob instanceof PModelBuildJob)
	    	refresh();
	}   

	// project content changed 
	public void projectContentChanged() {
	    if (pmodel == null) return;
	    PNamed p = callbacks().getProject().child(pmodel.name());
	    if (p != pmodel) {
	    	pmodel = null;
		refresh();
	    }
	}

	// refresh text widget
	public void refresh() {
	    StringBuffer buf = new StringBuffer();
	    loadText(buf);
	    jtext.setText(buf.toString());
	}

	// load text buffer
	private void loadText(StringBuffer buf) {
	    if (pmodel == null) {
	    	buf.append("No model selected");
		return;
	    }
	    buf.append("Model=" + pmodel.name() + "\n");
	    ASModel amodel = pmodel.rt();
	    VarQuery vq = new VarQuery(amodel);
	    buf.append(vq.getText()); // query all vars
	}
}

		    
