/*
 * @(#)Connect.java
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 1999-2004 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDcreator.java for details.
 */

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

/**
 * The start of a connection to CDWserver.
 *
 * @version 20041012
 * @author Jörg P. M. Haeger
 */
public class Connect extends Command {
	private String serverName;
	private int portNo;
	JOptionPane pane;
	static JEditorPane viewer;
	static JDialog greetingDialog;

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

	private static JComponent createGreetingPane(String info) {
		JPanel vbox = new JPanel();
		vbox.setLayout(new BoxLayout(vbox, BoxLayout.Y_AXIS));

		String title = info;
		int p = title.indexOf("\n");
		if (p >= 0) {
			title = title.substring(0, p);
			info = info.substring(p + 1);
		}

		String license = "";
		int p2 = title.indexOf("(");
		if (p2 >= 0) {
			license = title.substring(p2 + 1, title.length() - 1);
			title = title.substring(0, p2);
		}
		vbox.add(new JLabel("<html>"
			+ "<b><font size=\"+1\">"
				+ title
			+ "</font></b>"
			+ "</html>"));
		if (license.indexOf("Home Use") >= 0
				|| license.indexOf("privat") >= 0)
			vbox.add(new JLabel("<html>"
				+ "<font size=\"-1\">"
					+ license
				+ "</font>"
				+ "</html>"));
		vbox.add(Box.createVerticalStrut(10));

		viewer = CDcreator.getHTML("welcome.html");
		if (viewer == null || CDcreator.isNetscapeVM()) {
			String type = "text/plain";
			if (info.toLowerCase().indexOf("<html>") >= 0)
				type = "text/html";
			viewer = new JEditorPane(type, info);
			viewer.setEditable(false);
		}
		viewer.setAlignmentX(Box.LEFT_ALIGNMENT);
//		viewer.setPreferredSize(new Dimension(400, 200));
		viewer.addHyperlinkListener(
			new HyperlinkListener() {
				public void hyperlinkUpdate(HyperlinkEvent e) {
//					System.out.println("link = " + e.getURL());
					String str = e.getDescription();
					if (e.getEventType()
							== HyperlinkEvent.EventType.ACTIVATED)
						if (str.indexOf(".jnlp?") >= 0) {
							int p0 = str.indexOf(".jnlp?");
							String args = str.substring(p0 + 6) + "&";
							p0 = args.toUpperCase().indexOf("URL=");
							int p1 = args.indexOf("&", p0);
							if (p0 >= 0 && p1 >= 0)
								CDcreator.projectURL
									= args.substring(p0 + 4, p1);
							CDcreator.oneClick
								= args.indexOf("oneClick=on") >= 0;
							greetingDialog.setVisible(false);
						}
						else
						if (e.getDescription().startsWith("http://"))
							CDcreator.showDocument(e.getURL());
						else {
							JEditorPane pane
								= CDcreator.getHTML(e.getDescription());
							try {
								viewer.setPage(pane.getPage());
							}
							catch (Exception e2) { }
						}
			}
		});
		JScrollPane scroller = new JScrollPane();
		scroller.setPreferredSize(new Dimension(440, 200));
		scroller.setAlignmentX(Box.LEFT_ALIGNMENT);
		scroller.getViewport().add(viewer);
		vbox.add(scroller);

		return vbox;
	}

	int getInt(String str, String key) {
		int p0 = str.indexOf(key + "=");
		if (p0 < 0)
			return -1;
		p0 += key.length() + 1;
		int res = 0;
		while (p0 < str.length()) {
			char ch = str.charAt(p0++);
			if (ch < '0' || ch  > '9')
				break;
			res = 10 * res + ch - '0';
		}
		return res;
	}

	void processHint(String str) {
		super.processHint(str);
		Integer val;
		if (str.indexOf("anonymousUse") >= 0)
			CDcreator.anonymousUse = true;
		else
		if (str.indexOf("askForProjectInfo") >= 0)
			CDcreator.askForProjectInfo = true;
		else
		if (str.indexOf("audioCDSupport") >= 0)
			CDcreator.audioCDSupport = true;
		else
		if (str.indexOf("cdrdao") >= 0)
			CDcreator.cdrdao = true;
		else
		if (str.indexOf("copy") >= 0)
			CDcreator.copySupport = true;
		else
		if ((val = parse(str, "defaultSpeed", 1)) != null) {
			Options.speed = val.intValue();
			if ((val = parse(str, "defaultSpeed", 2)) != null) {
				Options.speedAudio = val.intValue();
				if ((val = parse(str, "defaultSpeed", 3)) != null)
					Options.speedCDRW = val.intValue();
			}
		}
		else
		if (str.indexOf("DVD") >= 0)
			CDcreator.supportedMedia = str + " ";
		else
		if (str.indexOf("managedAccounts") >= 0)
			CDcreator.managedAccounts = true;
		else
		if ((val = parse(str, "maxCopies")) != null)
			CDcreator.maxCopies = val.intValue();
		else
		if ((val = parse(str, "maxMBTransferPerProject")) != null)
			CDcreator.maxMBTransferPerProject = val.intValue();
		else
		if ((val = parse(str, "maxSpeed")) != null)
			CDcreator.maxSpeed = val.intValue();
		else
		if (str.indexOf("mp3") >= 0)
			CDcreator.mp3Support = true;
		else
		if (str.indexOf("overburnSupport") >= 0)
			CDcreator.overburnSupport = true;
		else
		if (str.indexOf("saveImageAs") >= 0)
			CDcreator.saveImageAs = true;
		else
		if (str.indexOf("verify") >= 0)
			CDcreator.verifySupport = true;
		else
		if (str.indexOf("writeProtection") >= 0)
			CDcreator.writeProtection = true;
		else {
			int n = getInt(str, "md5");
			if (n < 0)
				n = 2;
			CDcreator.MD5FileSupport = n > 0;
			Options.MD5File = Options.MD5FileDefault = n > 1;
		}
	}

	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, cancelOption);
		JDialog dialog = pane.createDialog(
			CDcreator.mainWin, i18n("titleTryToConnect"));
		showDialog(dialog);
		new JLabel("<html><b>Preload HTML viewer</b></html>");

		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 BufferedInputStream(
				socket.getInputStream());

			CDcreator.outStream = new DataOutputStream(
				socket.getOutputStream());
			CDcreator.outStream.writeBytes("CDWP\n");

			// 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, okOption);
			dialog = pane.createDialog(
				CDcreator.mainWin, i18n("error"));
		}
		else
		if (!lastResultOK()) {
			CDcreator.socket = null;
			pane = new JOptionPane(
				MainWin.createViewer(lastResult),
				JOptionPane.WARNING_MESSAGE,
				JOptionPane.DEFAULT_OPTION,
				null, okOption, okOption[0]);
			dialog = pane.createDialog(
				CDcreator.mainWin, i18n("error"));
		}
		else {
			execCommand("client " + Version.product
				+ " " + Version.version);
			execCommand("client LnF "
				+ UIManager.getSystemLookAndFeelClassName());
			execCommand("client config" + Config.log);
			execCommand("setProtocol 5");
			execCommand("system " + CDcreator.osName
				+ " " + CDcreator.osVersion);
			execCommand("vm " + CDcreator.vmName
				+ " " + CDcreator.vmVersion);
			execCommand("user noID " + State.userID);

			pane = new JOptionPane(
				createGreetingPane(infoStr),
				JOptionPane.INFORMATION_MESSAGE,
				JOptionPane.DEFAULT_OPTION,
				null, okOption);
			dialog = pane.createDialog(CDcreator.mainWin,
				i18n("titleConnectedTo"));
			greetingDialog = dialog;
		}
		if (!CDcreator.oneClick)
			showInfoWin(dialog);
		super.run();
	}
}
