/**
 *#########################################################################
 *
 * A component of the Gatherer application, part of the Greenstone digital
 * library suite from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * Author: Greenstone Digital Library, University of Waikato
 *
 * Copyright (C) 1999 New Zealand Digital Library Project
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *########################################################################
 */

package org.greenstone.gatherer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.*;
import javax.swing.JApplet;

import java.io.*;
//import javax.jnlp.*;
import javax.swing.*;
import org.greenstone.gatherer.util.JarTools;
import org.greenstone.gatherer.util.UnzipTools;
import org.greenstone.gatherer.util.Utility;

import java.util.*;

public class WebGatherer
{

    protected static String fullLibraryURL(String address) 
    {
	String full_address = "";

        // make sure the URL has protocol, host, and file
        if (address.startsWith("http:") || address.startsWith("https:")) {
            // the address has all the necessary components
	    full_address = address;
        } 
	/*else if (address.startsWith("/")) {
            // there is not protocol and host
			// JNLP replacement for applet getDocumentBase, https://stackoverflow.com/questions/6371493/java-web-start-getdocumentbase
			BasicService bs = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
			URL document = bs.getCodeBase();
	    int port_no = document.getPort();

            String port = (port_no>0) ? ":" + port_no : "";
            full_address = "http://" + document.getHost() + port  + address;
	}*/

	return full_address;
    }

	static private String getParameter(String cmd_arg, String flagName) {
		int start_index = cmd_arg.indexOf(flagName) + flagName.length();
		cmd_arg = cmd_arg.substring(start_index);
		return cmd_arg;
	}

    /* This is the entry point for the Java Web Start version of GLI (a rewrite of GathererApplet as a Java Web Start application) */
    static public void main(String cmdArgs[])
    {
	Gatherer gatherer = null;
	JarTools.initialise(WebGatherer.class); 
	
	String gwcgi_arg = null;
	String gsdl3_arg = "false"; // String, "true" or "false"
	String windowsHome_arg = null;
	String debug_arg = "false"; // String, "true" or "false"
	
	for(int i = 0; i<cmdArgs.length; i++) {
		///System.err.println("*** cmdarg " + i + " = " + cmdArgs[i]);
		
		if(cmdArgs[i].contains("gwcgi=")) {
			gwcgi_arg = getParameter(cmdArgs[i], "gwcgi=");
		} else if(cmdArgs[i].contains("gsdl3=")) {
			gsdl3_arg = getParameter(cmdArgs[i], "gsdl3=");
		} else if(cmdArgs[i].contains("windowsHome=")) {
			windowsHome_arg = getParameter(cmdArgs[i], "windowsHome=");
		} else if(cmdArgs[i].contains("debug=")) {
			debug_arg = getParameter(cmdArgs[i], "debug=");
		}
	}
	
	///System.err.println("*** gwcgi_arg = " + gwcgi_arg);
	///System.err.println("*** gsdl3_arg = " + gsdl3_arg);
	// More debugging:
	Map<String,String> envMap = System.getenv();
	Set<Map.Entry<String,String>> entries = envMap.entrySet();
	Iterator<Map.Entry<String, String>> i = entries.iterator();
	System.err.println("*** ENVIRONMENT: ");
	while(i.hasNext()) {
		Map.Entry<String, String> entry = i.next();
		String key = entry.getKey();
		String value = entry.getValue();
		System.err.println("*** key = " + key);
		System.err.println("*** val = " + value);
	}
	// End debugging

	// Check if the user has agreed to the requested security settings
	try {
	    // Work-around to reduce number of 
	    // 'Could not lock user prefs' error messages.
	    // Thanks to Walter Schatz from the java forums.
	    System.setProperty("java.util.prefs.syncInterval","2000000");
	}
	catch (Exception exception) {
	    System.err.println("Greenstone Librarian Interface Applet deactivated");
	    return;
	}

	// Ensure platform specific LAF
	try {
	    //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
	}
	catch (Exception exception) {
	    exception.printStackTrace();
	}

	// Determine the GLI user directory path
	String gli_user_directory_path = System.getProperty("user.home") + File.separator;
        if (Utility.isWindows()) {
	    String windows_home_parameter = windowsHome_arg;
	    if (windows_home_parameter != null && !windows_home_parameter.equals("")) {
		gli_user_directory_path = windows_home_parameter + File.separator + "GLI" + File.separator;
	    }
	    else {
		gli_user_directory_path += "Application Data" + File.separator + "Greenstone" + File.separator + "GLI" + File.separator;
	    }
	}
        else {
            gli_user_directory_path += ".gli" + File.separator;
        }
	Gatherer.setGLIUserDirectoryPath(gli_user_directory_path);

	// If we're running as an applet we don't have a local GLI, so use the user directory path as the GLI path
	Gatherer.setGLIDirectoryPath(gli_user_directory_path);

	// Set some global variables so we know how we're running
	Gatherer.isApplet = false;
	String library_url_string = fullLibraryURL(gwcgi_arg);

	String gs3 = gsdl3_arg; // but we'll pass -use_remote_greenstone below, to ensure we use the branch of the code that does connects a GLI on a client machine to a remote GS3 server
	boolean isGS3 = (gs3 == null || !gs3.equals("true")) ? false : true;

	String gliserver_url_string;
	if(!isGS3) {
	    gliserver_url_string = library_url_string.substring(0, library_url_string.lastIndexOf('/') + 1) + "gliserver.pl";
	} else {
	    gliserver_url_string = library_url_string + "/cgi-bin/gliserver.pl";
	}

        // String debug_param = debug_arg;
        // if ((debug_param != null) && (debug_param.matches("true"))) {
        //     go.debug = true;
        // }

	String[] args;
	if(!isGS3) {
	    String[] gs2_args = { 
		"-use_remote_greenstone",
		"-gliserver_url", gliserver_url_string,
		"-library_url", library_url_string,
		// "-debug",
	    };
	    args = gs2_args;
	} else { // >= GS3
	    String[] gs3_args = {
		"-use_remote_greenstone",
		"-gliserver_url", gliserver_url_string,
		"-library_url", library_url_string,
		"-gsdl3",
		//"-debug",
	    };
	    args = gs3_args;
	}
	
	// Create an instance of the Gatherer class, which will parse the args and prepare the rest of the GLI
	gatherer = new Gatherer(args); // Do this early as it will also call Gatherer.setCollectDirectoryPath(), because we need that to have been set hereafter.
				
	File collect_directory = new File(Gatherer.getCollectDirectoryPath());
	if (!collect_directory.exists()) {
	    if (JarTools.isInJar("collect.zip")) {
		// Dig out collect.zip from JAR file and unzip it (thereby
		// creating collect directory and descendants.
		//   This is done to seed gsdl home folder with config files
		//   for documented example collections so "base this on
		//   existing collection" works
		unzipFromJar("collect.zip", Gatherer.getGLIUserDirectoryPath());
	    }
	    else {
		// Prepare an empty collect dir for use
		if (!collect_directory.mkdir()) {
		    System.err.println("Warning: Unable to make directory: " + collect_directory);
		}
	    }
	}

	File metadata_directory = new File(Gatherer.getGLIMetadataDirectoryPath());
	if (!metadata_directory.exists()) {
	    // dig out metadata.zip from JAR file and unzip it
	    unzipFromJar("metadata.zip", Gatherer.getGLIDirectoryPath());
	}

	gatherer.openGUI();
    }


    /** 
     * Method which unzips a given metadata resource.
     * @param jar_zip_fname The name of the jar file as a <strong>String</strong>.
     * @param dst_dir The destination directory for unzipping, also as a <strong>String</strong>.
     * @see JarTools.extractFromJar(String, String, boolean)
     */
    static public void unzipFromJar(String jar_zip_fname, String dst_dir)
    {
	if (!dst_dir.endsWith(File.separator)) {
	    dst_dir += File.separator;
	}

	JarTools.extractFromJar(jar_zip_fname, dst_dir, true);
	UnzipTools.unzipFile(dst_dir + jar_zip_fname, dst_dir);
    }
}
