
// Project: webCDwriter - Network CD Writing
// Author: Jörg Haeger
//	joerg.haeger@Uni-Bielefeld.de

import java.io.*;
import java.net.*;
import javax.swing.*;

public class Connect extends Command
{
	private String serverName;
	private int portNo;
	JOptionPane pane;

	public Connect(String serverName, int portNo)
	{
		this.serverName = serverName;
		this.portNo = portNo;
	}

	void processHint(String str)
	{
		super.processHint(str);
		Integer val;
		if (str.indexOf("mp3") >= 0)
			CDcreator.mp3Support = true;
		else
		if ((val = parse(str, "defaultSpeed")) != null)
			Options.speed = val.intValue();
		else
		if ((val = parse(str, "maxSpeed")) != null)
			CDcreator.maxSpeed = val.intValue();
	}

	void processInfo(String str)
	{
		super.processInfo(str);
		if (pane != null)
			pane.setMessage(infoStr);
	}

	public void run()
	{
		// try to connect to CDWserver
		pane = new JOptionPane(
			i18n("tryToConnect"),
			JOptionPane.INFORMATION_MESSAGE,
			JOptionPane.DEFAULT_OPTION,
			null, cancelButton);
		JDialog dialog = pane.createDialog(
			CDcreator.mainWin, i18n("titleTryToConnect"));
		showDialog(dialog);

		Socket socket;
		try {
			try {
				socket = new Socket(serverName, portNo);
			} catch (Exception e) {
				netscape.security.PrivilegeManager
					.enablePrivilege(
						"UniversalConnect");
				socket = new Socket(serverName, portNo);
			}

			CDcreator.inStream = new BufferedReader(
				new InputStreamReader(
					socket.getInputStream()));

			CDcreator.outStream = new DataOutputStream(
				socket.getOutputStream());

			// get greeting
			readResult();
		}
		catch (Exception e)
		{
			socket = null;
		}
		CDcreator.socket = socket;
		hideDialog();

		if (socket == null)
		{
			status = ERROR;
			Version.showDebugInfo("no Connection");
			pane = new JOptionPane(
				i18n("noConnection"),
				JOptionPane.WARNING_MESSAGE,
				JOptionPane.DEFAULT_OPTION,
				null, okButton);
			dialog = pane.createDialog(
				CDcreator.mainWin, i18n("error"));
		}
		else
		if (!lastResultOK())
		{
			CDcreator.socket = null;
			pane = new JOptionPane(
				lastResult,
				JOptionPane.WARNING_MESSAGE,
				JOptionPane.DEFAULT_OPTION,
				null, okButton);
			dialog = pane.createDialog(
				CDcreator.mainWin, i18n("error"));
		}
		else
		{
			execCommand("client " + Version.product
				+ " " + Version.version);
			execCommand("setProtocol 2");
			execCommand("system " + CDcreator.osName
				+ " " + CDcreator.osVersion);
			execCommand("vm " + CDcreator.vmName
				+ " " + CDcreator.vmVersion);
			execCommand("user noID " + CDcreator.userName);
			execCommand("login " + userID
				+ " " + userPassword);

			pane = new JOptionPane(
				infoStr,
				JOptionPane.INFORMATION_MESSAGE,
				JOptionPane.DEFAULT_OPTION,
				null, okButton);
			dialog = pane.createDialog(CDcreator.mainWin,
				i18n("titleConnectedTo"));
		}
		showInfoWin(dialog);
		super.run();
	}
}
