/*
 * Copyright (C) 2008 Alan Huan-Chun Peng Hsu ( http://bitdojo.net )
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package utils;

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
import javax.swing.text.*;

/**
 * ProxyHelper: A simple helper class for proxy authentication.
 * 
 * To set the proxy form your code, simply call the method
 * ProxyHelper.showProxyLoginFrameAndWait(). This will display 
 * a login window for the user to enter username and password.
 *
 * The calling thread will block until the login window is closed.
 * 
 * The default proxy settings can be found below, at the beginning 
 * of the class.
 *
 * @version 1.03 (2008-09-19)
 * @author Alan Huan-Chun Peng Hsu
 */
public class ProxyHelper {

	public static String proxy_user = "username";
	public static char[] proxy_pass = "password".toCharArray();
	public static String proxy_server = "wwwproxy.student.unimelb.edu.au";
	public static String proxy_port = "8000";
	public static String proxy_nonProxyHosts = "localhost|192.*|127.*";
	
	/**
	 * Sets the proxy server using System.setProperty
	 */
	public static void setProxy(){
		
		System.setProperty("proxySet", "true");
		System.setProperty("http.proxyHost", proxy_server);
		System.setProperty("http.proxyPort", proxy_port);
		System.setProperty("http.nonProxyHosts", proxy_nonProxyHosts);
		
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(proxy_user, proxy_pass);
			}
		};
		
		Authenticator.setDefault(auth);
		
		System.out.println("Using proxy: " + proxy_user + "@" + proxy_server + ":" + proxy_port);
			    
	}
	
	/**
	 * Displays the proxy login window and cause the calling thread to block
	 */
	public static void showProxyLoginFrameAndWait(){
		
		threadWait = true;
		
		new Thread(){
			public void run(){
				new LoginFrame();
			}
		}.run();
		
		while(threadWait){
			try{
				Thread.sleep(100);
			} catch (Exception e) { }
		}
				
	}
	
	private static boolean threadWait = false;
	
	/**
	 * A simple login window
	 */
	private static class LoginFrame 
		extends JFrame 
		implements ActionListener, FocusListener, KeyListener {
		
		private JTextField field_user = new JTextField();
		private JPasswordField field_pass = new JPasswordField();
		private JButton button_ok = new JButton("Ok");
		
		public LoginFrame(){
			
			this.setTitle("Proxy Login");
			this.setLocationByPlatform(true);
			this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			this.setResizable(false);
			this.setLayout(new FlowLayout());
			this.addKeyListener(this);
			
			field_user.setColumns(10);
			field_user.addFocusListener(this);
			field_user.addKeyListener(this);
			field_user.setText(proxy_user);
			
			field_pass.setColumns(10);
			field_pass.addFocusListener(this);
			field_pass.addKeyListener(this);
			field_pass.setText(new String(proxy_pass));
			
			button_ok.setActionCommand("setProxy");
			button_ok.addActionListener(this);
			
			this.add(field_user);
			this.add(field_pass);
			this.add(button_ok);
			
			this.pack();
			this.setVisible(true);
			
		}

		public void dispose(){
		
			threadWait = false;
			super.dispose();
		}
		
		private void doLoginButtonPressed(){
			
			proxy_user = field_user.getText();
			proxy_pass = field_pass.getPassword();
			setProxy();
			threadWait = false;
			this.setVisible(false);
		}
		
		public void actionPerformed(ActionEvent e) {
			
			if(e.getActionCommand().equals("setProxy")){
				doLoginButtonPressed();
			}
			
		}
		
		public void focusGained(FocusEvent e) {
			
			Component c = e.getComponent();
			
			if(c instanceof JTextComponent){
				((JTextComponent)c).selectAll();
			}
		}

		public void focusLost(FocusEvent e) {}

		public void keyPressed(KeyEvent e) {
		
			if(e.getKeyCode() == KeyEvent.VK_ENTER){
				doLoginButtonPressed();
			}
		}

		public void keyReleased(KeyEvent e) { }

		public void keyTyped(KeyEvent e) { }
		
	}
	
}

