/**
 *#########################################################################
 *
 * 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: John Thompson, 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.applet.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.*;
import javax.swing.JApplet;

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


public class GathererApplet extends JApplet implements ActionListener
{
    private Gatherer gatherer = null;


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

        // make sure the URL has protocol, host, and file
        if (address.startsWith("http:")) {
            // the address has all the necessary components
	    full_address = address;
        } 
	else if (address.startsWith("/")) {
            // there is not protocol and host
            URL document = getDocumentBase();
	    int port_no = document.getPort();

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

	return full_address;
    }


    /* This is the entry point for the GLI applet */
    public void init()
    {
	JarTools.initialise(this); 

	// 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) {
	    getContentPane().add(new JLabel("Greenstone Librarian Interface Applet deactivated", JLabel.CENTER));
	    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 = getParameter("windowsHome");
	    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 = true;
	String library_url_string = fullLibraryURL(getParameter("gwcgi"));

	String gs3 = getParameter("gsdl3");
	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 = getParameter("debug");
        // 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;
	}
	
	// For WebGatherer.java, which uses Java Web Start over JNLP to run the repurposed "applet" as application,
	// it turned out that for GS3, we need the collectionDirectoryPath set for the subsequent code to work.
	// In WebGatherer.java, moved the instantiation of the Gatherer object here, but to avoid major changes to
	// this GathererApplet.java class, just calling the relevant line in Gatherer() constructor at this stage:
	Gatherer.setCollectDirectoryPath(Gatherer.getGLIUserDirectoryPath() + "collect" + File.separator);
	
	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());
	}

	// Create an instance of the Gatherer class, which will parse the args and prepare the rest of the GLI
	gatherer = new Gatherer(args);

	// Create a button for the user to press to open the GLI GUI
	JButton launch_GLI_button = new JButton("Launch Greenstone Librarian Interface ...");
	launch_GLI_button.addActionListener(this);
	getContentPane().add(launch_GLI_button);
    }


    public void start() 
    {
	System.err.println("Start called");
    }


    public void stop()
    {
	System.err.println("Stop called");
    }


    public void destroy()
    {
	System.err.println("Destroy called");
	gatherer.exit();
	gatherer = null;
	System.err.println("Done gatherer exit.");
    }


    public void actionPerformed(ActionEvent e)
    {
	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);
    }
}
