package org.greenstone.gatherer.download;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Properties;
import org.greenstone.gatherer.cdm.Argument;
import org.greenstone.gatherer.Configuration;
import org.greenstone.gatherer.DebugStream;
import org.greenstone.gatherer.Dictionary;
import org.greenstone.gatherer.Gatherer;
import org.greenstone.gatherer.greenstone.LocalGreenstone;
import org.greenstone.gatherer.gui.*;
import org.greenstone.gatherer.util.SafeProcess;
import org.greenstone.gatherer.util.Utility;

public class ServerInfoDialog extends JDialog
{    
    static private Dimension SIZE = new Dimension(500, 300);
    private String url;
    private String mode;
    private JPanel info_list_pane;
    private JTextArea info_text_area;
    private JScrollPane info_scroll_pane;
    private JDialog info_dialog;
    private Download download;
    private Properties proxy_urls;
    
    public ServerInfoDialog(String url, Properties proxy_urls, String mode, Download download) {
	super();
	this.url = url;
	this.mode = mode;
        this.download = download;
        this.proxy_urls = proxy_urls;
	this.info_dialog = this;
	
	this.setSize(SIZE);

 	JButton close_button = new GLIButton(Dictionary.get("General.Close"),Dictionary.get("General.Close_Tooltip"));
 	close_button.setEnabled(true); 
	close_button.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent event) {
		    info_dialog.dispose();
		}
	    });
	
	JPanel button_pane = new JPanel();
	button_pane.setLayout(new FlowLayout());
	button_pane.setBorder(BorderFactory.createEtchedBorder());
	button_pane.add(close_button);
	
	info_list_pane = new JPanel();
	info_list_pane.setLayout(new BoxLayout(info_list_pane, BoxLayout.Y_AXIS));
	info_list_pane.setBorder(BorderFactory.createEtchedBorder());
	info_text_area = new JTextArea();
	info_list_pane.add(info_text_area);
	info_text_area.setEditable(false);
	getServerInfo();

	info_scroll_pane = new JScrollPane(info_list_pane);
	
	JPanel information_pane = new JPanel();
	information_pane.setLayout(new BorderLayout());
	information_pane.setBorder(BorderFactory.createEtchedBorder());
	information_pane.add(info_scroll_pane,BorderLayout.CENTER);
	
	JPanel main_pane = new JPanel();
	main_pane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
	main_pane.setLayout(new BorderLayout());
	main_pane.add(information_pane,BorderLayout.CENTER);
	main_pane.add(button_pane,BorderLayout.SOUTH);

	Container main_container = this.getContentPane();
	main_container.add(main_pane);
	
	// Show
	Dimension screen_size = Configuration.screen_size;
	setLocation((screen_size.width - SIZE.width) / 2, (screen_size.height - SIZE.height) / 2);

	TestingPreparation.setIndividualSubcomponentNames(this, info_text_area);
	
	setVisible(true);

    }

    private void getServerInfo()
    {
	ArrayList commands = new ArrayList();
	commands.add(Configuration.perl_path);
	commands.add("-S");
	commands.add(LocalGreenstone.getBinScriptDirectoryPath()+"downloadfrom.pl");
	commands.add("-info");
	commands.add("-download_mode");
	commands.add(mode);
	
       	ArrayList all_arg = download.getArguments(true,false);
	for (int i = 0; i < all_arg.size(); i++) {
	    Argument argument = (Argument) all_arg.get(i);
	    
	    if(argument.isAssigned()) {
		commands.add("-" + argument.getName());
		if(argument.getType() != Argument.FLAG) {
		    commands.add(argument.getValue());
		}
	    }
	}
	
	String[] command = (String[]) commands.toArray(new String[0]);
	DebugStream.println("Getting server info: "+commands);
	try {	    
	    SafeProcess prcs = null;

	    if (proxy_urls.size() != 0) {
		// Specify proxies as environment variables
		// Need to manually specify GSDLHOME and GSDLOS also
		String[] env = new String[4+proxy_urls.size()];

		env[0] = "GSDLHOME=" + Configuration.gsdl_path;
		env[1] = "GSDLOS=" + Gatherer.client_operating_system;
		// teach it where the wgetrc file lives, in gs2build/bin/<os>:
		env[2] = "GSWGETRC=" + System.getenv("GSWGETRC"); //LocalGreenstone.getBinOSDirectoryPath(Gatherer.client_operating_system)+"wgetrc";
		// Issue discovered on Windows: If PATH is not made available to perl, so that wget or something else needed by
		// WgetDownload.pm's open3()  call is not on the PATH, then the perl open() call to run wget fails.
		// So make PATH available to get open3() working:
		env[3] = "PATH="+System.getenv("PATH");		

		int next_index = 4;
		String proxy_url = proxy_urls.getProperty("HTTP");
		if(proxy_url != null) {
		    env[next_index] = "http_proxy="+proxy_url;
		    next_index++;
		}
		proxy_url = proxy_urls.getProperty("HTTPS");
		if(proxy_url != null) {
		    env[next_index] = "https_proxy="+proxy_url;
		    next_index++;
		}
		proxy_url = proxy_urls.getProperty("FTP");
		if(proxy_url != null) {
		    env[next_index] = "ftp_proxy="+proxy_url;
		    next_index++;
		}				
		
		prcs = new SafeProcess(command, env, null);
	    } else {
		// Will inherit the GLI's environment, with GSDLHOME and GSDLOS set
		prcs = new SafeProcess(command);
	    }
	    
	    // special processing of Process' stderr stream: 
	    // Search the process standard error stream and seach for two particular occurences.
	    int exitVal = prcs.runProcess(null, new ProcErrStreamLineByLineHandler());
	    
	} catch (Exception ioe) {
	    ioe.printStackTrace();
	}
	
    }

    private class ProcErrStreamLineByLineHandler extends SafeProcess.LineByLineHandler
    {
	public ProcErrStreamLineByLineHandler() {
	    super(SafeProcess.STDERR); // sets this.source
	}

	public void gotLine(String line) {
	    // Check the current line from the standard error stream and seach for two particular occurences.
	    if (!line.trim().equals("<<Finished>>")) {
	      Gatherer.invokeInEDT_replacesProceedInCurrThread(
	       "ServerInfoDialog.ProcErrStreamLineByLineHandler.gotLine()",
	       Gatherer.ASYNC,
	       new Runnable() {
		   public void run() {
		       /*
			 JLabel a_label = new JLabel(line);
			 a_label.setAlignmentX(Component.LEFT_ALIGNMENT);
			 ServerInfoDialog.this.info_list_pane.add(a_label);
		       */
		       if(!line.trim().equals("")) {
			   ServerInfoDialog.this.info_text_area.append(line + "\n");
		       }
		   }
	       });
	    }
	}
	public void gotException(Exception e) {
	    e.printStackTrace();
	}
    }
}
