package rpn;

import java.net.*;
import java.io.*;
import rpn.basic.Item;
import rpn.basic.ErrItem;
import rpn.graphics.*;

public class PanelCalculator extends Calculator 
		implements Runnable, GraphicsCalculator  {
	int N = 0, Nmax = 100;
	public CalculatorPanel vc;
	URL loadBase = null;
	
	public PanelCalculator(CalculatorPanel vc, 
		URL loadBase, 
		ItemInterpreter it) {
		super(it);
		this.vc = vc;
		this.loadBase = loadBase;
	}
	
	public CalculatorCanvas getCanvas() {
		GraphicsFrame gf = vc.gfxFrame;
		if (gf != null) {
			return(gf.canvas);
		} else return(null);
	}
	
	// -----------------------------------------------
	
	public boolean running = false;
	public int sleepTime = 1;
	public Item it;
	
	public void run() {
		while (running && (it = getItem()) != null) {
			if (procDepth == 0) {
				it.exec();
			} else {
				it.store();
			}
			try {
				Thread.sleep(sleepTime);
			} catch (InterruptedException ex) { ; }
		}
		if (it == null) {
			vc.caFinish();
			running = false;
		}
	}
	
	Thread p;
	
	public void start() {
		p = new Thread(this);
		running = true;
		p.start();
	}
	
	public void stop() {
		running = false;
		p = null;
	}

	public void pause() {
		vc.caStop();
		stop();
	}
	
	public Item step() {
		it = getItem();
		if (it != null) {
			if (procDepth == 0) {
				it.exec();
			} else {
				it.store();
			}
		}
		return(it);
	}
	
	// -----------------------------------------------
	
	public void error(Item it, int n) {
		if (!(it instanceof ErrItem)) {
			output(new ErrItem(this, it, n));
		} else {
			output(it);
		}
		pause();
	}
	
	// s = file name relative to directory of html
	public String load(String s) {
		try {
			URL url = new URL(loadBase, s);
			InputStream is = url.openStream();
			StringBuffer sb = new StringBuffer();
			int c = is.read();
			while (c != -1) {
				sb.append((char) c);
				c = is.read();
			}
			return(new String(sb));
		} catch(MalformedURLException ue) { 
			return(null);
		}
		catch(IOException ie) {
			return(null);
		} 
		
	}
	
	public void output(Item it) {
		vc.caOutput(it.toString());
	}
	
	public void output(String s) {
		vc.caOutput(s);
	}
}
