
package org.openspml.browser;

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

import java.util.List;
import org.openspml.util.*;

public class ConnectPanel extends JPanel implements ActionListener {

    State _state;
    JTextField _url;
    JComboBox _history;
    JTextField _username;
    JPasswordField _password;
    JButton _test;

    public ConnectPanel(State s) {

	setLayout(new BorderLayout());
	_state = s;

        SimpleForm form = new SimpleForm();
        add(form, BorderLayout.WEST);

        _url = new JTextField(null, 40);
        form.add("Server URL", _url);
        _url.addActionListener(this);

	Vector saved = readSavedUrls();
	if (saved == null)
	    _history = new JComboBox();
	else
	    _history = new JComboBox(saved);
        _history.addActionListener(this);
        form.add("Saved URLs", _history);

        _username = new JTextField(null, 40);
        form.add("Username", _username);
        _username.addActionListener(this);

        _password = new JPasswordField(null, 40);
        form.add("Password", _password);
        _password.addActionListener(this);

        _test = new JButton("Test");
        _test.addActionListener(this);
        form.add("", _test);

        // handy for testing, though we don't want it to go out this way
        // should try to support configurable "profiles"

	if (System.getProperty("spml.lighthouse") != null) {
            _url.setText(State.LIGHTHOUSE_URL);
            _username.setText(State.LIGHTHOUSE_USER);
            _password.setText(State.LIGHTHOUSE_PASSWORD);
            refreshConnection();
        }

    }

    private Vector readSavedUrls() {
	Vector v = null;
	try {
	    String saved = Util.readFile("urls.txt");
	    List urls = Util.decodeNewlineString(saved, true);
	    urls.add(0, "");
	    v = new Vector(urls);
	}
	catch (Throwable t) {
            // usually file not found, this is common when first        
            // starting, ignore
	    //System.out.println(t.toString());
	}
	return v;
    }

    private void refreshConnection() {

        _state.setConnection(SwingUtil.getText(_url),
                             SwingUtil.getText(_username),
                             SwingUtil.getText(_password));
    }

    public void actionPerformed(ActionEvent e) {

	if (e.getSource() == _test) {
	    refreshConnection();
	    _state.testConnection();
	}
	else if (e.getSource() == _history) {
	    _url.setText((String)_history.getSelectedItem());
	    _username.setText(null);
	    _password.setText(null);
	    refreshConnection();
	}
    }

}
