/*
 * Copyright 2009-2010 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.lisp.applet;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import javax.swing.JApplet;

import net.morilib.lisp.Scheme;

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2011/02/03
 */
public class SchlushApplet extends JApplet {

	//
	private static final long serialVersionUID = 5219031968106173690L;

	/**
	 * 
	 */
	protected void initSchlushApplet() {
		// do nothing
	}

	/* (non-Javadoc)
	 * @see java.applet.Applet#init()
	 */
	@Override
	public final void init() {
		SchlushAppletFrame frm;
		final Scheme scheme = Scheme.newInstance();
		Runnable run = new Runnable() {

			public void run() {
				String sprog = getParameter("scheme-program");
				String senc  = getParameter("scheme-encoding");
				InputStream ins = null;
				Reader rd = null;

				try {
					if(sprog == null) {
						throw new AppletInitializeException(
								"program must be specified");
					}
					sprog = sprog.replaceAll("\\.scm$", "");
					sprog = sprog.replace('.', '/');
					sprog = "/" + sprog + ".scm";
					ins = SchlushApplet.class.getResourceAsStream(
							sprog);
					if(ins == null) {
						throw new AppletInitializeException(
								"program not found:" + sprog);
					} else if(senc != null) {
						rd = new InputStreamReader(ins, senc);
					} else {
						rd = new InputStreamReader(ins);
					}

					//
					scheme.readFile(rd);
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException(e);
				} catch (IOException e) {
					throw new RuntimeException(e);
				} finally {
					if(ins != null) {
						try {
							ins.close();
						} catch (IOException e) {
							throw new RuntimeException();
						}
					}
				}
			}

		};

		super.init();
		initSchlushApplet();
		frm = new SchlushAppletFrame(SchlushApplet.this);
		scheme.set("*applet*", frm);
		setContentPane(frm.createPanel());
		new Thread(run).start();
	}

}
