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

import javax.swing.*;

/**
 * LoginDialog
 *
 * @version 20031022
 * @author Jörg P. M. Haeger
 */
public class LoginDialog {
	public static String i18n(String key) {
		return CDcreator.i18n(key);
	}

	private static boolean login(String userID, String password) {
		if (userID.length() == 0) {
			JOptionPane.showMessageDialog(
				CDcreator.mainWin,
				i18n("LDNoUserName"),
				i18n("error"),
				JOptionPane.ERROR_MESSAGE);
			return false;
		}
		else
		if (password.length() == 0) {
			JOptionPane.showMessageDialog(
				CDcreator.mainWin,
				i18n("LDNoPassword"),
				i18n("error"),
				JOptionPane.ERROR_MESSAGE);
			return false;
		}
		else {
			try {
				new Login(userID, password).exec();
				return true;
			}
			catch (CommandError e) {
				JOptionPane.showMessageDialog(
					CDcreator.mainWin,
					i18n("LDFailed"),
					i18n("error"),
					JOptionPane.ERROR_MESSAGE);
				return false;
			}
		}
	}

	public static boolean show() {
		JPanel vp = new JPanel();
		vp.setLayout(new BoxLayout(vp, BoxLayout.Y_AXIS));
//		vp.setBorder(
//			BorderFactory.createEmptyBorder(3, 40, 5, 5));
		vp.setAlignmentX(Box.LEFT_ALIGNMENT);

		JTextField userIDField = new JTextField(State.userID);
		userIDField.setColumns(15);
		vp.add(Dialog.createLabelItemBox(
			new JLabel(i18n("LDUserName")), 120,
			userIDField));
		vp.add(Box.createVerticalStrut(10));

		final JPasswordField passwordField = new JPasswordField("");
		passwordField.setColumns(15);
		vp.add(Dialog.createLabelItemBox(
			new JLabel(i18n("LDPassword")), 120,
			passwordField));

		String options[] = {
			i18n("cancel"), i18n("LDNewAccount"), i18n("OK") };
		String options2[] = {
			i18n("cancel"), i18n("OK") };
		if (CDcreator.managedAccounts)
			options = options2;

		while (true) {
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					passwordField.requestFocus();
				}
			});
			int res = JOptionPane.showOptionDialog(
				CDcreator.mainWin,
				vp, i18n("LDTitle"), JOptionPane.DEFAULT_OPTION,
				JOptionPane.PLAIN_MESSAGE, null,
				options, options[options.length - 1]);
			if (res == 0 || res == JOptionPane.CLOSED_OPTION)
				return false;
			if (res == 1 && !CDcreator.managedAccounts) {
				NewAccountDialog d = new NewAccountDialog();
				CDcreator.view.center(d);
				d.show();
				continue;
			}
			if (login(userIDField.getText(), passwordField.getText()))
				return true;
		}
	}
}
