/* Copyright (c) 1997-2004
 Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
 http://www.math.tu-berlin.de/polymake,  mailto:polymake@math.tu-berlin.de
 
 This program is free software; you can redistribute it and/or modify it
 under the terms of the GNU General Public License as published by the
 Free Software Foundation; either version 2, or (at your option) any
 later version: http://www.gnu.org/licenses/gpl.txt.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 $Project: polymake $$Id: SpringEmbedderControl.java,v 1.8 2005/11/18 17:02:27 wotzlaw Exp $
 */

package de.tuberlin.polymake.graph;

import java.awt.Frame;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.channels.Pipe;

import de.tuberlin.polymake.common.PointSet;
import de.tuberlin.polymake.common.JavaviewControl;
import de.tuberlin.polymake.common.SimpleGeometryParser;

/**
 * This class ???
 *
 * @author Thilo Schr&ouml;der
 */
public class SpringEmbedderControl extends JavaviewControl {
	
	public SpringEmbedderControl( 
			BufferedReader psReader, 
			BufferedReader clientReader, 
			Pipe.SinkChannel sink) throws IOException{
		super(psReader,clientReader,sink);
		parser = new SimpleGeometryParser(new String[]{"continue", "viscosity", "inertion", 
				"repulsion", "orientation"});
		
		
		try {
			putMessage("read " + geom.getName()+"\n",true);
		} catch( IOException ex ) {
			ex.printStackTrace();
		}
	}
	
	public void update() throws IOException {
		
		PointSet newGeom = parser.parse(clientReader);
		synchronized(clientQueue){
			if(parser.getError() != null) {
				clientQueue.clear();
			} else {
				clientQueue.popFront();
			}
			if(!clientQueue.isEmpty()) {
				bbuf.flip();
				pipeSink.write(bbuf);
			}
		}
		if (!(frameMap.containsKey(newGeom.getName())) ||
				!(((SpringEmbedderFrame)frameMap.get(newGeom.getName())).isDisplayable())) {
			SpringEmbedderFrame tmpFrame = new SpringEmbedderFrame(geom,parser.getParameters(),parser.getInteractiveParameters(),this);
			tmpFrame.update(newGeom, parser.getParameters());
			frameMap.put(geom.getName(),tmpFrame);
			tmpFrame.setVisible(true);
		} else {
			SpringEmbedderFrame tmpFrame = (SpringEmbedderFrame) frameMap.get(geom.getName());
			if (tmpFrame.isVisible() || tmpFrame.getState() == Frame.ICONIFIED) {
				tmpFrame.setState(Frame.NORMAL);
			}
			tmpFrame.setVisible(true);	    if(parser.getWarning() != null) {
				tmpFrame.setStatus(parser.getWarning());
			} else {
				if(parser.getError() != null) {
					tmpFrame.setStatus(parser.getError());
				}
			}
			tmpFrame.update(newGeom, parser.getParameters());
			if(parser.getParam("continue").equals("1") && tmpFrame.autoRecompute()) {
				putMessage("s continue 1\nx\n",true);
			}
		}
	}
}
