
package applets;

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import mri.v3ds.*;


public class Decode3dsApplet extends Applet implements ActionListener
{
	String[] mNames = { "objects.3ds", "jelyfish.3ds" };
	Choice mChoice = null;
	Button[] mButtons = null;
	TextArea mTextArea = null;
	String mNL = null;


	public void init()
	{
		mNL = System.getProperty("line.separator");

		mTextArea = new TextArea("", 22, 74);
		mTextArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
		add(mTextArea);

		mChoice = new Choice();
		mChoice.add("Decode everything");
		mChoice.add("Only used params.");
		mChoice.add("Only used params. and chunks");
		add(mChoice);

		mButtons = new Button[ mNames.length ];
		for(int i=0; i < mButtons.length; i++) {
			mButtons[i] = new Button("Decode \"" + mNames[i] + "\"");
			mButtons[i].setActionCommand(mNames[i]);
			mButtons[i].addActionListener(this);
			add(mButtons[i]);
		}

		mTextArea.setText("Press a button to decode.");
	}

	public void actionPerformed(ActionEvent e)
	{
		mTextArea.setText("Downloading and decoding...");

		int level;
		switch(mChoice.getSelectedIndex()) {
		default:
		case 0: level = Scene3ds.DECODE_ALL; break;
		case 1: level = Scene3ds.DECODE_USED_PARAMS; break;
		case 2: level = Scene3ds.DECODE_USED_PARAMS_AND_CHUNKS; break;
		}

		String str = doDecode(e.getActionCommand(), level);

		mTextArea.setText(str);
	}


	private String doDecode(String file_name, int level)
	{

		/*
		 *  We will receive the text decode in this object
		 */
		TextDecode3ds decode = new TextDecode3ds();

		String text = null;
		URL url = null;
		InputStream stream;

		text = mNL + "Decoding 3D Studio R4 3ds-file: " + file_name + mNL;


		/*
		 *  Construct a URL to the specified 3ds-file
		 */
		try {
			url = new URL(getCodeBase().toString() + file_name);
		}
		catch(MalformedURLException e) {
			text = text + "URL is bad: " + e.getMessage() + mNL;
			return text;
		}
		text = text + "URL is: " + url.toString() + mNL + mNL;


		/*
		 *  Open an InputStream to the 3ds-file
		 */
		try {
			stream = url.openStream();
		}
		catch(IOException e) {
			text = text + "Problems opening URL: " + e.getMessage() + mNL;
			return text;
		}


		/*
		 *  Parse the 3ds-file and produce the textural decode at the  
		 *  same time. 
		 *
		 *  Note! There are other Scene3ds constructors also, reading
		 *        the 3ds-file data from a local File or from a byte[]
		 *        array. See the API documentation for details.
		 */
		try {
			Scene3ds scene = new Scene3ds(stream, decode, level);
		}
		catch(Exception3ds e) {
			text = text + decode.text();
			text = text + "Exception: " + e.getMessage() + mNL;
			return text;
		}

		return text + decode.text();
	}
}


